Skip to content

Commit

Permalink
feat: add json-server
Browse files Browse the repository at this point in the history
  • Loading branch information
TomatoVan committed Nov 8, 2023
1 parent 70ed6f1 commit 24347a2
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 0 deletions.
30 changes: 30 additions & 0 deletions json-server/db.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"posts": [
{
"id": 1,
"title": "json-server",
"userId": 1
},
{
"id": 2,
"title": "json-server",
"userId": 2
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
}
],
"users": [
{
"id": 1,
"username": "admin",
"password": "123"
}
],
"profile": { "name": "typicode" }
}

57 changes: 57 additions & 0 deletions json-server/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
const fs = require('fs');
const jsonServer = require('json-server');
const path = require('path');

const server = jsonServer.create();

const router = jsonServer.router(path.resolve(__dirname, 'db.json'));

server.use(jsonServer.defaults({}));
server.use(jsonServer.bodyParser);

// Нужно для небольшой задержки, чтобы запрос проходил не мгновенно, имитация реального апи
server.use(async (req, res, next) => {
await new Promise((res) => {
setTimeout(res, 800);
});
next();
});

// Эндпоинт для логина
server.post('/login', (req, res) => {
try {
const { username, password } = req.body;
const db = JSON.parse(fs.readFileSync(path.resolve(__dirname, 'db.json'), 'UTF-8'));
const { users = [] } = db;

const userFromBd = users.find(
(user) => user.username === username && user.password === password,
);

if (userFromBd) {
return res.json(userFromBd);
}

return res.status(403).json({ message: 'User not found' });
} catch (e) {
console.log(e);
return res.status(500).json({ message: e.message });
}
});

// проверяем, авторизован ли пользователь
// eslint-disable-next-line
server.use((req, res, next) => {
if (!req.headers.authorization) {
return res.status(403).json({ message: 'AUTH ERROR' });
}

next();
});

server.use(router);

// запуск сервера
server.listen(8000, () => {
console.log('server is running on 8000 port');
});

0 comments on commit 24347a2

Please sign in to comment.