1. npm install json-server and ts-node
Copy npm i json-server ts-node --save-dev
2. Make a server.ts file in a new folder called server
Copy 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
Copy {
"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
Copy /// abbreviated
scripts: {
...
"server": "ts-node ./server/server.ts"
...
}
//abbreviated
5. Start the server and leave it running