ng6-udm-mock
TypeScript icon, indicating that this package has built-in type declarations

3.0.2 • Public • Published

ng6-udm-mock Angular6 Service Library to use JsonPlaceholder and json-server

MIT License

ng6-udm-mock is a service library for using JsonPlaceholder and json-server by Angular6.

Overview

  • ng6-udm-mock is a tool for those who want to use JsonPlaceholder service by Angular6
  • ng6-udm-mock has methods for getting, adding, updating and deleting data in all the tables, ie Post, Comment, Album, Photo, Todo, User tables in JsonPlaceholder.
  • You can test your own data by using json-server
  • You can change the access destination by the environment variable

Registered Methods

Here are the methods registered in this library.

  // =============== Post ================
  public getAllPosts(): Observable<UdmPost[]>
  public getPost(id: number): Observable<UdmPost>
  public getPostsByUserId(userId: number): Observable<UdmPost[]>
  public addPost(userId: number, title: string, body: string): Observable<HttpResponse<UdmPost>>
  public updatePost(post: UdmPost): Observable<number>
  public deletePost(post: UdmPost | number): Observable<number>

  // =============== Comment ================
  public getAllComments(): Observable<UdmComment[]>
  public getComment(id: number): Observable<UdmComment>
  public getCommentsByPostId(postId: number): Observable<UdmComment[]>
  public addComment(postId: number, name: string, email: string, body: string): Observable<HttpResponse<UdmComment>>
  public updateComment(comment: UdmComment): Observable<number>
  public deleteComment(comment: UdmComment | number): Observable<number>

  // ============== Album ==========================
  public getAllAlbums(): Observable<UdmAlbum[]>
  public getAlbum(id: number): Observable<UdmAlbum>
  public getAlbumsByUserId(userId: number): Observable<UdmAlbum[]>
  public addAlbum(userId: number, title: string): Observable<HttpResponse<UdmAlbum>>
  public updateAlbum(album: UdmAlbum): Observable<number>
  public deleteAlbum(album: UdmAlbum | number): Observable<number>

  // ============== Photo ==========================
  public getAllPhotos(): Observable<UdmPhoto[]>
  public getPhoto(id: number): Observable<UdmPhoto>
  public getPhotosByAlbumId(albumId: number): Observable<UdmPhoto[]>
  public addPhoto(albumId: number, title: string, url: string, thumbnailUrl: string): Observable<HttpResponse<UdmPhoto>>
  public updatePhoto(photo: UdmPhoto): Observable<number>
  public deletePhoto(photo: UdmPhoto | number): Observable<number>

  // ============== Todo ==========================
  public getAllTodos(): Observable<UdmTodo[]>
  public getTodo(id: number): Observable<UdmTodo>
  public getTodosByUserId(userId: number): Observable<UdmTodo[]>
  public addTodo(userId: number, title: string, completed: boolean ): Observable<HttpResponse<UdmTodo>>
  public updateTodo(todo: UdmTodo): Observable<number>
  public deleteTodo(todo: UdmTodo | number): Observable<number>

  // ============== User ==========================

  public getAllUsers(): Observable<UdmUser[]>
  public getUser(id: number): Observable<UdmUser>
  public getUsersByUserName(username: string): Observable<UdmUser[]>
  public addUser(name: string,
                username: string,
                email: string,
                address: UdmAddress,
                phone: string,
                website: string,
                company: UdmCompany ):
                Observable<HttpResponse<UdmUser>>
  public updateUser(user: UdmUser): Observable<number>
  public deleteUser(user: UdmUser | number): Observable<number>

Registered Interfaces

Here are the interfaces registered in this library.

export interface UdmPost {
    id: number;
    userId: number;
    title: string;
    body: string;
}

export interface UdmComment {
    id: number;
    postId: number;
    name: string;
    email: string;
    body: string;
}

export interface UdmAlbum {
    id: number;
    userId: number;
    title: string;
}

export interface UdmPhoto {
    id: number;
    albumId: number;
    title: string;
    url: string;
    thumbnailUrl: string;
}

export interface UdmTodo {
    id: number;
    userId: number;
    title: string;
    completed: boolean;
}

export interface UdmGeo {
    lat: string;
    lng: string;
}

export interface UdmAddress {
    street: string;
    suite: string;
    city: string;
    zipcode: string;
    geo: UdmGeo;
}


export interface UdmCompany {
    name: string;
    catchPhrase: string;
    bs: string;
}

export interface UdmUser {
    id: number;
    name: string;
    username: string;
    email: string;
    address: UdmAddress;
    phone: string;
    website: string;
    company: UdmCompany;
}

Prerequisite

  • Node.js
  • TypeScript2
  • Angular6
  • json-server (If you want to use your own data)

Installation

To install this library, run:

$ npm install ng6-udm-mock --save

To install json-server, run:

$ npm install json-server 

Configuration

In the library itself, no access destination is set. This access destination is set by the environment variable of the application project using this library. Specifically, it is set in the src/environments/environment.ts file.

If you only want to access the JsonPlaceholder site and retrieve the data, set udmMockBaseUrl to https: // jsonplaceholder.typicode.com.

If you wish to use the data addition, update and delete functions, create your own data with the same structure as the data on the JsonPlaceholder site, and when you start json-server, set the access destination to udmMockBaseUrl.

If you start the server locally without specifying the port number, localhost:3000 is the access destination, so set it.

Set destination url in environment.ts file

export const environment = {
  production: false,
  udmMockBaseUrl: 'https://jsonplaceholder.typicode.com'
  // udmMockBaseUrl: 'http://localhost:3000'
};

Sample app.component.ts

The following is a sample program that uses this library.

Important points are as follows.

   - Import Ng6UdmMockService    - Import Interfaces    - Define variables (including arrays) corresponding to each interface    - Make the service variable in Constructor

  • Initialize BaseUrl with ngOnInit method (call setBaseUrl method)

Based on these points, please refer to the following sources.

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { tap, map } from 'rxjs/operators';
import { HttpErrorResponse } from '@angular/common/http';

import { Ng6UdmMockService } from 'ng6-udm-mock';
import { UdmPost, UdmComment, UdmAlbum, UdmPhoto, UdmTodo,
  UdmGeo, UdmAddress, UdmCompany, UdmUser } from 'ng6-udm-mock';

import { environment } from '../environments/environment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app';

  private posts: UdmPost[];
  private post: UdmPost;
  private comments: UdmComment[];
  private comment: UdmComment;
  private albums: UdmAlbum[];
  private album: UdmAlbum;
  private photos: UdmPhoto[];
  private photo: UdmPhoto;
  private todos: UdmTodo[];
  private todo: UdmTodo;
  private users: UdmUser[];
  private user: UdmUser;

  constructor(private sv: Ng6UdmMockService) {

  }

  ngOnInit() {
    this.sv.setBaseUrl(environment.udmMockBaseUrl);
  }
// ============== Post ==================

  public GetAllPosts() {
    this.sv.getAllPosts()
      .subscribe(
        dt => {
          this.posts = dt;
        },
        (err: HttpErrorResponse) => {
          if (err.error instanceof Error) {
            console.log('An error occurred:', err.error.message);
          } else {
            console.log('Status code:', err.status);
            console.log('Response body:', err.error);
          }
        },
        () => {
          console.log('Done successfully');
        }
      );
  }

  public GetPost(id: number) {
    this.sv.getPost(id)
    .subscribe(
      dt => {
        this.post = dt;
      },
      (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          console.log('An error occurred:', err.error.message);
        } else {
          console.log('Status code:', err.status);
          console.log('Response body:', err.error);
        }
      },
      () => {
        console.log('Done successfully');
      }
    );
  }

  public GetPostsByUserId(userId: number) {
    this.sv.getPostsByUserId(userId)
    .subscribe(
      dt => {
        this.posts = dt;
      },
      (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          console.log('An error occurred:', err.error.message);
        } else {
          console.log('Status code:', err.status);
          console.log('Response body:', err.error);
        }
      },
      () => {
        console.log('Done successfully');
      }
    );
  }

  public AddPost(userId: number, title: string, body: string) {
    this.sv.addPost(userId, title, body)
    .subscribe(
      dt => {
        this.post = dt.body;
      },
      (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          console.log('An error occurred:', err.error.message);
        } else {
          console.log('Status code:', err.status);
          console.log('Response body:', err.error);
        }
      },
      () => {
        console.log('Done successfully');
      }
    );
  }

  public UpdatePost() {
    const post: UdmPost = {
      id: 4,
      userId: 1,
      title: 'test01 - updated 01',
      body: 'This is updated text'
    };
    this.sv.updatePost(post)
    .subscribe(
      dt => {
        console.log(dt);
      },
      (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          console.log('An error occurred:', err.error.message);
        } else {
          console.log('Status code:', err.status);
          console.log('Response body:', err.error);
        }
      },
      () => {
        console.log('Done successfully');
      }
    );
  }

  public DeletePost() {
    this.sv.deletePost(4)
    .subscribe(
      dt => {
        console.log(dt);
      },
      (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          console.log('An error occurred:', err.error.message);
        } else {
          console.log('Status code:', err.status);
          console.log('Response body:', err.error);
        }
      },
      () => {
        console.log('Done successfully');
      }
    );
  }

Version

  • ng6-udm-mock : 3.0
  • node.js : 8.11
  • @angular/cli : 6.0
  • TypeScript : 2.7

Reference

Change Log

  • 2018.9.1 version 3.0 uploaded

Copyright

copyright 2018 by Shuichi Ohtsu (DigiPub Japan)

License

MIT © Shuichi Ohtsu

Readme

Keywords

none

Package Sidebar

Install

npm i ng6-udm-mock

Weekly Downloads

0

Version

3.0.2

License

none

Unpacked Size

362 kB

Total Files

23

Last publish

Collaborators

  • ohtsu