Category model and controllers

This commit is contained in:
unknown 2021-05-22 19:04:34 +02:00
parent 5c948e1a68
commit 100f274d96
8 changed files with 164 additions and 4 deletions

1
api.js
View File

@ -14,6 +14,7 @@ api.use(express.json());
api.use('/api/apps', require('./routes/apps'));
api.use('/api/config', require('./routes/config'));
api.use('/api/weather', require('./routes/weather'));
api.use('/api/categories', require('./routes/category'));
// Custom error handler
api.use(errorHandler);

83
controllers/category.js Normal file
View File

@ -0,0 +1,83 @@
const asyncWrapper = require('../middleware/asyncWrapper');
const ErrorResponse = require('../utils/ErrorResponse');
const Category = require('../models/Category');
const Bookmark = require('../models/Bookmark');
// @desc Create new category
// @route POST /api/categories
// @access Public
exports.createCategory = asyncWrapper(async (req, res, next) => {
const category = await Category.create(req.body);
res.status(201).json({
success: true,
data: category
})
})
// @desc Get all categories
// @route GET /api/categories
// @access Public
exports.getCategories = asyncWrapper(async (req, res, next) => {
// const categories = await Category.findAll({
// include: Bookmark
// });
const categories = await Category.findAll();
res.status(200).json({
success: true,
data: categories
})
})
// @desc Get single category
// @route GET /api/categories/:id
// @access Public
exports.getCategory = asyncWrapper(async (req, res, next) => {
const category = await Category.findOne({
where: { id: req.params.id }
});
if (!category) {
return next(new ErrorResponse(`Category with id of ${req.params.id} was not found`, 404))
}
res.status(200).json({
success: true,
data: category
})
})
// @desc Update category
// @route PUT /api/categories/:id
// @access Public
exports.updateCategory = asyncWrapper(async (req, res, next) => {
let category = await Category.findOne({
where: { id: req.params.id }
});
if (!category) {
return next(new ErrorResponse(`Category with id of ${req.params.id} was not found`, 404))
}
category = await category.update({ ...req.body });
res.status(200).json({
success: true,
data: category
})
})
// @desc Delete category
// @route DELETE /api/categories/:id
// @access Public
exports.deleteCategory = asyncWrapper(async (req, res, next) => {
await Category.destroy({
where: { id: req.params.id }
})
res.status(200).json({
success: true,
data: {}
})
})

View File

@ -5,10 +5,10 @@ const errorHandler = (err, req, res, next) => {
let error = { ...err };
error.message = err.message;
if (error.errors[0].type === 'unique violation') {
const msg = error.errors[0].message;
error = new ErrorResponse(`Field ${msg}`, 400);
}
// if (error.errors[0].type === 'unique violation') {
// const msg = error.errors[0].message;
// error = new ErrorResponse(`Field ${msg}`, 400);
// }
console.log(error);
console.log(`${err}`.bgRed);

21
models/Bookmark.js Normal file
View File

@ -0,0 +1,21 @@
const { DataTypes } = require('sequelize');
const { sequelize } = require('../db');
const Bookmark = sequelize.define('Bookmark', {
name: {
type: DataTypes.STRING,
allowNull: false
},
url: {
type: DataTypes.STRING,
allowNull: false
},
categoryId: {
type: DataTypes.INTEGER,
allowNull: false
}
}, {
tableName: 'bookmarks'
});
module.exports = Bookmark;

17
models/Category.js Normal file
View File

@ -0,0 +1,17 @@
const { DataTypes } = require('sequelize');
const { sequelize } = require('../db');
const Category = sequelize.define('Category', {
name: {
type: DataTypes.STRING,
allowNull: false
},
isPinned: {
type: DataTypes.BOOLEAN,
defaultValue: false
}
}, {
tableName: 'categories'
});
module.exports = Category;

13
models/associateModels.js Normal file
View File

@ -0,0 +1,13 @@
const Category = require('./Category');
const Bookmark = require('./Bookmark');
const associateModels = () => {
// Category <> Bookmark
Bookmark.belongsTo(Category, { foreignKey: 'categoryId' });
Category.hasMany(Bookmark, {
as: 'bookmarks',
foreignKey: 'categoryId'
});
}
module.exports = associateModels;

23
routes/category.js Normal file
View File

@ -0,0 +1,23 @@
const express = require('express');
const router = express.Router();
const {
createCategory,
getCategories,
getCategory,
updateCategory,
deleteCategory
} = require('../controllers/category');
router
.route('/')
.post(createCategory)
.get(getCategories);
router
.route('/:id')
.get(getCategory)
.put(updateCategory)
.delete(deleteCategory);
module.exports = router;

View File

@ -4,11 +4,13 @@ const api = require('./api');
const jobs = require('./utils/jobs');
const Socket = require('./Socket');
const Sockets = require('./Sockets');
const associateModels = require('./models/associateModels');
require('dotenv').config();
const PORT = process.env.PORT || 5005;
connectDB();
associateModels();
// Create server for Express API and WebSockets
const server = http.createServer();