Skip to content

Commit

Permalink
json-server
Browse files Browse the repository at this point in the history
  • Loading branch information
veronikaa-kuznetsova committed Jun 6, 2024
1 parent 6387e1c commit 988f928
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 0 deletions.
29 changes: 29 additions & 0 deletions json-server/db.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"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');
});
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"main": "index.js",
"scripts": {
"start": "webpack serve --env port=3000",
"start:dev:server": "node ./json-server/index.js",
"build:prod": "webpack --env mode=production",
"build:dev": "webpack --env mode=development",
"lint:ts": "eslint \"**/*.{ts,tsx}\"",
Expand Down

0 comments on commit 988f928

Please sign in to comment.