본문 바로가기

Frontend/JavaScript

NPM - JSON Server

반응형

JSON server is one of the NPM packages that provides a server for testing. It stores data in a JSON format and is very easy to work with

List of Contents

Implementation

Installing the Package

npm i json-server

Setting Up the NPM command

To run the server, we need a command. Open the package.json file and add the script below.

 

"<command>":"json-server --watch <fileName>.json"


※ Json server uses port 3000 as React does

So, if you use this with React add the option to change the port to avoid a collision.

"<command>":"json-server --watch <fileName>.json --port <port>"


Running the Server

Run the command you set in the script

 

By default, it will create test data in the file (if not just add the file on the root level)

Every key inside the object represents a table. For test purposes, I have added more data to the posts

Working with Data

Run the server and send an HTTP request.

 

Angular

Let's see how we can do the CRUD with Angular.

 

Model

To work with angular easier, we will create a model. Note that Json Server requires an 'id' field so make sure you add the field with 'id' as its name.

 

export interface Post {  
  id?: string;
  title: string;
  content: string;
  imagePath?: string;
  auth?: string;
}

Service

Add a service class (using either the CLI command below or adding the file by yourself)

 

ng g service <name>

Add necessary properties and a constructor with dependency injections

 

url: string = 'http://localhost:4040/posts/';
posts!: Post[];

constructor(private http: HttpClient, private router: Router) {}

▶ GET (List)

getPosts() {
  this.http.get<Post[]>(this.url).subscribe((data) => {
    this.posts = data;  
    this.postUpdated.next(this.posts);
  });
}

▶ GET (Item)

getPost(id: string) {
  return this.http.get<Post>(this.url + id);
}

▶ POST

addPost(title: string, content: string) {
  const post: Post = {
    id: '3',
    title: title,
    content: content,
  };       
  this.http.post(this.url, post).subscribe((result) => {      
    this.router.navigate(['/']);
  });
}

▶ PUT

updatePost(
  id: string,
  : string,
  content: string,    
) {
  let post:Post = {
    id: id,
    title: title,
    content: content,
    } 
  }

  this.http.put(this.url + id, post).subscribe((result) => {      
    this.router.navigate(['/'])
  });
}

▶ DELETE

deletePost(id: string) {
  this.http.delete(this.url + id).subscribe((result) => {    
    this.router.navigate(['/']);
  });
}

React

Let's see how we can do the CRUD with React.

 

const URL = 'http://localhost:4040/posts/'

▶ GET (List)

const fetchData = async () => {
  const res = await fetch(URL)
  const data = await res.json()  
}

▶ GET (Item)

const fetchData = async (id) => {
  const res = await fetch(URL + id)
  const data = await res.json()  
}

▶ POST

const addFeed = async (newFeed) => {
  await fetch(URL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(newFeed)
  })  
}

▶ PUT

const updateFeed = async (id, newFeed) => {
  await fetch(URL + id, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(newFeed)
  })  
}

▶ DELETE

const deleteFeed = async (id) => {
  await fetch(URL + id, {
    method: 'DELETE'
  })  
}

As we have seen in this writing, The JSON server is an easy way to add a server to your front application to give it a test. 

 


References

json-server - npm (npmjs.com)

 

json-server

Get a full fake REST API with zero coding in less than 30 seconds. Latest version: 0.17.3, last published: 2 months ago. Start using json-server in your project by running `npm i json-server`. There are 311 other projects in the npm registry using json-ser

www.npmjs.com

 

 

 

728x90
반응형

'Frontend > JavaScript' 카테고리의 다른 글

Drag and Drop  (1) 2023.07.05
JavaScript Module - Button Ripple Effect  (1) 2023.07.03
JavaScript Module - Text Wave Effect  (2) 2023.04.05
Client Side Storage - Indexed DB  (0) 2023.03.31
Client Side Storage - Web Storage  (0) 2023.03.31