Skip to content

Commit

Permalink
add json-server, update card
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkMelior committed Mar 21, 2024
1 parent 4161888 commit f510523
Show file tree
Hide file tree
Showing 14 changed files with 548 additions and 100 deletions.
31 changes: 31 additions & 0 deletions json-server/db.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"products": [
{
"id": 1,
"src": "/",
"links": [
{
"src": "exampleLink1",
"market": "ozon"
},
{
"src": "exampleLink2",
"market": "yandex"
}
],
"images": ["cat.png", "cat.png", "cat.png"],
"title": "Example Title 1",
"rating": 4.5,
"reviewCount": 100,
"price": 50,
"oldPrice": 60
}
],
"users": [
{
"id": 1,
"username": "admin",
"password": "123"
}
]
}
59 changes: 59 additions & 0 deletions json-server/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
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');
});
Loading

0 comments on commit f510523

Please sign in to comment.