Enterprise Angular Applications with NgRx and Nx
  • Introduction
  • Introduction
    • Introduction
    • Course Description
    • Resources
    • 0 - Environment Setup
    • 1a - Brief Introduction To Angular
    • 1b - Brief Introduction To Angular
    • 1c - Brief Introduction To Angular
    • 2 - Creating an Nx Workspace
    • 3 - Generating components and Nx lib
    • 4 - Add JSON server
    • 5 - Angular Services
    • 6 - Angular Material
    • 7 - Reactive Forms
    • 8 - Layout Lib and BehaviorSubjects
    • 9 - Route Guards and Products Lib
    • 10 - NgRx Introduction
    • 11 - Adding NgRx to Nx App
    • 12 - Strong Typing the State and Actions
    • 13 - NgRx Effects
    • 14 - NgRx Selectors
    • 15 - Add Products NgRx Feature Module
    • 16 - Entity State Adapter
    • 17 - Router Store
    • 18 - Deploying An Nx Monorepo
Powered by GitBook
On this page
  • 1. npm install json-server and ts-node
  • 2. Make a server.ts file in a new folder called server
  • 3. Add a file called db.json
  • 4. Add the below script to the scripts in the package.json
  • 5. Start the server and leave it running
  • 6. Navigate to http://localhost:3000
  • 8. Commit your code
  1. Introduction

4 - Add JSON server

Previous3 - Generating components and Nx libNext5 - Angular Services

Last updated 6 years ago

1. npm install json-server and ts-node

  • add json-server and ts-node

npm i json-server ts-node --save-dev
  • Add a folder called server to the root directory and paste in the below code

2. Make a server.ts file in a new folder called server

  • Make a new folder called server

  • Make file called server.ts in the new server folder and paste in the below code. You do not need to study or learn this min node express app it is just to have a mock backend.

server/server.ts
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('server/db.json');
const middlewares = jsonServer.defaults();
const db = require('./db.json');
const fs = require('fs');

server.use(middlewares);
server.use(jsonServer.bodyParser);

server.post('/login', (req, res, next) => { 
  const users = readUsers();

  const user = users.filter(
    u => u.username === req.body.username && u.password === req.body.password
  )[0];

  if (user) {
    res.send({ ...formatUser(user), token: checkIfAdmin(user) });
  } else {
    res.status(401).send('Incorrect username or password');
  }
});

server.post('/register', (req, res) => {
  const users = readUsers();
  const user = users.filter(u => u.username === req.body.username)[0];

  if (user === undefined || user === null) {
    res.send({
      ...formatUser(req.body),
      token: checkIfAdmin(req.body)
    });
    db.users.push(req.body);
  } else {
    res.status(500).send('User already exists');
  }
});

server.use('/users', (req, res, next) => {
  if (isAuthorized(req) || req.query.bypassAuth === 'true') {
    next();
  } else {
    res.sendStatus(401);
  }
});

server.use(router);
server.listen(3000, () => {
  console.log('JSON Server is running');
});

function formatUser(user) {
  delete user.password;
  user.role = user.username === 'admin'
    ? 'admin'
    : 'user';
  return user;
}

function checkIfAdmin(user, bypassToken = false) {
  return user.username === 'admin' || bypassToken === true
    ? 'admin-token'
    : 'user-token';
}

function isAuthorized(req) {
  return req.headers.authorization === 'admin-token' ? true : false;
}

function readUsers() {
  const dbRaw = fs.readFileSync('./server/db.json');  
  const users = JSON.parse(dbRaw).users
  return users;
}

3. Add a file called db.json

  • Make file called db.json for mock data in the new server folder

server/db.json
{
    "users": [
      {
        "id": 1,
        "username": "duncan",
        "country": "australia",
        "password": "123"
      },
      {
        "id": 2,
        "username": "sarah",
        "country": "england",
        "password": "123"
      },
      {
        "id": 3,
        "username": "admin",
        "country": "usa",
        "password": "123"
      },
      {
        "username": "test2",
        "password": "123",
        "id": 4
      }
    ],
    "profiles": [
      {
        "id": 1,
        "userId": 1,
        "job": "Plumber"
      },
      {
        "id": 2,
        "userId": 2,
        "job": "developer"
      },
      {
        "id": 3,
        "userId": 3,
        "job": "Manager"
      }
    ],
    "products": [
      {
        "id": 1,
        "name": "Spanner",
        "category": "tools"
      },
      {
        "id": 2,
        "name": "Hammer",
        "category": "tools"
      },
      {
        "id": 3,
        "name": "Screw driver",
        "category": "tools"
      },
      {
        "id": 4,
        "name": "Paint brush",
        "category": "paint"
      },
      {
        "id": 5,
        "name": "Paint roller",
        "category": "paint"
      },
      {
        "id": 6,
        "name": "Paint",
        "category": "paint"
      }
    ]
  }

4. Add the below script to the scripts in the package.json

package.json
/// abbreviated

scripts: {
   ...
    "server": "ts-node ./server/server.ts"
   ...
}

//abbreviated

5. Start the server and leave it running

  • Start the server and leave it running whenever you use the apps. It is easier to run in a seperate terminal to VS Code so when you refresh the IDE you do not kill this server.

npm run server
  • Check it is working.

8. Commit your code

6. Navigate to

http://localhost:3000
Server folder on root of project