create todo list

This commit is contained in:
Primakov Alexandr Alexandrovich 2025-01-18 16:50:58 +03:00
parent d88e680413
commit fb644b6f7b
8 changed files with 102 additions and 69 deletions

View File

@ -27,7 +27,7 @@ router.put('/new', (req, res) => {
return res.status(500).send('No data to update'); // Internal server error
}
indexedUpdatedData = { id: data.length, ...updatedData }; // Add the new dictionary to the array
const indexedUpdatedData = { id: data.length, ...updatedData }; // Add the new dictionary to the array
data.push(indexedUpdatedData); // Add the new dictionary to the array

View File

@ -3,37 +3,21 @@ const hash = require("pbkdf2-password")();
const { promisify } = require("node:util");
const jwt = require('jsonwebtoken')
const { AuthModel } = require("./model/todo/auth");
const { UserModel } = require("./model/todo/user");
const { getAnswer } = require("../../utils/common");
const { AuthModel } = require("./model/todo/auth");
const { TOKEN_KEY } = require('./const')
const { UserModel } = require("./model/todo/user");
const { requiredValidate } = require('./utils')
const router = Router();
const TOKEN_KEY = process.env.TOKEN_KEY || "asdfhoa-podh829438132 iahda98gauj dj2i3-111"
const requiredValidate =
(...fields) =>
(req, res, next) => {
const errors = []
fields.forEach((field) => {
if (!req.body[field]) {
errors.push(field);
}
});
if (errors.length) {
throw new Error(`Не все поля заполнены: ${errors.join(", ")}`);
} else {
next();
}
};
router.post(
"/signup",
requiredValidate("login", "password", "email"),
async (req, res, next) => {
const { login, password, email } = req.body;
const { login, password, email } = req.body
const user = await AuthModel.findOne({ login });
@ -47,10 +31,10 @@ router.post(
const user = await UserModel.create({ login, email });
await AuthModel.create({ login, hash, salt, userId: user.id });
res.json(getAnswer(null, { ok: true }));
});
res.json(getAnswer(null, { ok: true }))
})
}
);
)
function authenticate(login, pass, cb) {
AuthModel.findOne({ login }).populate('userId').exec().then((user) => {
@ -64,10 +48,10 @@ function authenticate(login, pass, cb) {
})
}
const auth = promisify(authenticate);
const auth = promisify(authenticate)
router.post('/signin', async (req, res) => {
const { login, password } = req.body;
router.post('/signin', requiredValidate('login', 'password'), async (req, res) => {
const { login, password } = req.body
const user = await auth(login, password)
@ -76,14 +60,14 @@ router.post('/signin', async (req, res) => {
}
const accessToken = jwt.sign({
...user.userId
...JSON.parse(JSON.stringify(user.userId)),
}, TOKEN_KEY, {
expiresIn: '12h'
})
res.json(getAnswer(null, {
user: user.userId,
token: accessToken
token: accessToken,
}))
})

View File

@ -4,3 +4,4 @@ exports.TODO_ITEM_MODEL_NAME = 'TODO_ITEM'
exports.TODO_AUTH_PASSWD_MODEL_NAME = 'TODO_AUTH_PASSWD'
exports.TODO_AUTH_USER_MODEL_NAME = 'TODO_AUTH_USER'
exports.TODO_AUTH_CHAT_MODEL_NAME = 'TODO_AUTH_CHAT'
exports.TOKEN_KEY = process.env.TOKEN_KEY || "asdfhoa-podh829438132-iahda98gauj-dj2i3-111"

View File

@ -5,7 +5,8 @@ const router = Router()
const todoRouter = require('./routes')
const authRouter = require('./auth')
router.use(todoRouter)
router.use('/auth', authRouter)
router.use(todoRouter)
module.exports = router

View File

@ -1,18 +1,22 @@
const { Schema, model } = require('mongoose')
const { TODO_LIST_MODEL_NAME, TODO_ITEM_MODEL_NAME } = require('../../const')
const { TODO_LIST_MODEL_NAME, TODO_ITEM_MODEL_NAME, TODO_AUTH_USER_MODEL_NAME } = require('../../const')
const schema = new Schema({
title: String,
created: {
type: Date, default: () => new Date().toISOString(),
},
createdBy: { type: Schema.Types.ObjectId, ref: TODO_AUTH_USER_MODEL_NAME },
items: [{ type: Schema.Types.ObjectId, ref: TODO_ITEM_MODEL_NAME }],
})
schema.set('toJSON', {
virtuals: true,
versionKey: false,
transform: function (doc, ret) {
delete ret._id
}
})
schema.virtual('id').get(function () {

View File

@ -0,0 +1,49 @@
const { Router } = require('express')
const { ListModel } = require('./model/todo/list')
const { ItemModel } = require('./model/todo/item')
const { getAnswer } = require('../../utils/common')
const router = Router()
// test - http://localhost:8033/todo/list
router.get('/list', async (req, res) => {
const items = await ListModel
.find({})
.populate('items')
.exec()
res.send(getAnswer(null, items))
})
// test - http://localhost:8033/todo/list/create/new%20List%20Name
router.get('/list/create/:title', async (req, res) => {
const { title } = req.params
const list = await ListModel.create({ title })
res.send(getAnswer(null, list))
})
// test - http://localhost:8033/todo/item/create/:listId/new%20one
router.get('/item/create/:listId/:name', async (req, res, next) => {
const { name, listId } = req.params
try {
const list = await ListModel.findById(listId)
if (!list) {
throw new Error('no such list')
}
const item = await ItemModel.create({ name })
list.addItem(item.id)
res.send(getAnswer(null, await ListModel.findById(listId)))
} catch (error) {
next(error)
}
})
module.exports = router

View File

@ -1,49 +1,24 @@
const { Router } = require('express')
const { expressjwt } = require('express-jwt')
const { getAnswer } = require('../../utils/common')
const { ListModel } = require('./model/todo/list')
const { ItemModel } = require('./model/todo/item')
const { getAnswer } = require('../../utils/common')
const { TOKEN_KEY } = require('./const')
const { requiredValidate } = require('./utils')
const router = Router()
// test - http://localhost:8033/todo/list
router.get('/list', async (req, res) => {
const items = await ListModel
.find({})
.populate('items')
.exec()
router.use(expressjwt({ secret: TOKEN_KEY, algorithms: ['HS256'] }))
res.send(getAnswer(null, items))
})
router.post('/', requiredValidate('title'), async (req, res) => {
const { title } = req.body
const userId = req.auth.id
// test - http://localhost:8033/todo/list/create/new%20List%20Name
router.get('/list/create/:title', async (req, res) => {
const { title } = req.params
const list = await ListModel.create({ title })
const list = await ListModel.create({ title, createdBy: userId })
res.send(getAnswer(null, list))
})
// test - http://localhost:8033/todo/item/create/:listId/new%20one
router.get('/item/create/:listId/:name', async (req, res, next) => {
const { name, listId } = req.params
try {
const list = await ListModel.findById(listId)
if (!list) {
throw new Error('no such list')
}
const item = await ItemModel.create({ name })
list.addItem(item.id)
res.send(getAnswer(null, await ListModel.findById(listId)))
} catch (error) {
next(error)
}
})
module.exports = router

View File

@ -0,0 +1,19 @@
const requiredValidate =
(...fields) =>
(req, res, next) => {
const errors = []
fields.forEach((field) => {
if (!req.body[field]) {
errors.push(field);
}
})
if (errors.length) {
throw new Error(`Не все поля заполнены: ${errors.join(", ")}`);
} else {
next()
}
}
module.exports.requiredValidate = requiredValidate;