SQLite database. App model and controller

This commit is contained in:
unknown 2021-05-10 17:47:26 +02:00
parent 8392c2422a
commit 2acc3b72ec
11 changed files with 1185 additions and 32 deletions

3
.gitignore vendored
View file

@ -1,2 +1,3 @@
node_modules/
.env
.env
*.sqlite

79
controllers/apps.js Normal file
View file

@ -0,0 +1,79 @@
const asyncWrapper = require('../middleware/asyncWrapper');
const ErrorResponse = require('../utils/ErrorResponse');
const App = require('../models/App');
// @desc Create new app
// @route POST /api/apps
// @access Public
exports.createApp = asyncWrapper(async (req, res, next) => {
const app = await App.create(req.body);
res.status(201).json({
success: true,
data: app
})
})
// @desc Get all apps
// @route GET /api/apps
// @access Public
exports.getApps = asyncWrapper(async (req, res, next) => {
const apps = await App.findAll();
res.status(200).json({
success: true,
data: apps
})
})
// @desc Get single app
// @route GET /api/apps/:id
// @access Public
exports.getApp = asyncWrapper(async (req, res, next) => {
const app = await App.findOne({
where: { id: req.params.id }
});
if (!app) {
return next(new ErrorResponse(`App with id of ${req.params.id} was not found`, 404));
}
res.status(200).json({
success: true,
data: app
})
})
// @desc Update app
// @route PUT /api/apps/:id
// @access Public
exports.updateApp = asyncWrapper(async (req, res, next) => {
let app = await App.findOne({
where: { id: req.params.id }
});
if (!app) {
return next(new ErrorResponse(`App with id of ${req.params.id} was not found`, 404));
}
app = await app.update({ ...req.body });
res.status(200).json({
success: true,
data: app
})
})
// @desc Delete app
// @route DELETE /api/apps/:id
// @access Public
exports.deleteApp = asyncWrapper(async (req, res, next) => {
await App.destroy({
where: { id: req.params.id }
})
res.status(200).json({
success: true,
data: {}
})
})

25
db.js Normal file
View file

@ -0,0 +1,25 @@
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: './db.sqlite'
});
const connectDB = async () => {
try {
await sequelize.authenticate({ logging: false });
console.log('Connected to database'.cyan.underline);
await sequelize.sync({
// alter: true,
logging: false
});
console.log('All models were synced'.cyan.underline);
} catch (error) {
console.error('Unable to connect to the database:', error);
}
}
module.exports = {
connectDB,
sequelize
};

View file

@ -0,0 +1,17 @@
// const asyncWrapper = foo => (req, res, next) => {
// return Promise
// .resolve(foo(req, res, next))
// .catch(next);
// }
// module.exports = asyncWrapper;
function asyncWrapper(foo) {
return function (req, res, next) {
return Promise
.resolve(foo(req, res, next))
.catch(next);
}
}
module.exports = asyncWrapper;

View file

@ -0,0 +1,15 @@
const ErrorResponse = require('../utils/ErrorResponse');
const errorHandler = (err, req, res, next) => {
let error = { ...err };
error.message = err.message;
console.log(err);
res.status(err.statusCode || 500).json({
success: false,
error: error.message || 'Server Error'
})
}
module.exports = errorHandler;

20
models/App.js Normal file
View file

@ -0,0 +1,20 @@
const { Sequelize, DataTypes } = require('sequelize');
const { sequelize } = require('../db');
const App = sequelize.define('App', {
name: {
type: DataTypes.STRING,
allowNull: false
},
url: {
type: DataTypes.STRING,
allowNull: false
},
icon: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: 'cancel'
}
});
module.exports = App;

1004
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -13,9 +13,12 @@
"license": "ISC",
"dependencies": {
"@types/express": "^4.17.11",
"colors": "^1.4.0",
"concurrently": "^6.0.2",
"dotenv": "^9.0.0",
"express": "^4.17.1"
"express": "^4.17.1",
"sequelize": "^6.6.2",
"sqlite3": "^5.0.2"
},
"devDependencies": {
"nodemon": "^2.0.7"

23
routes/apps.js Normal file
View file

@ -0,0 +1,23 @@
const express = require('express');
const router = express.Router();
const {
createApp,
getApps,
getApp,
updateApp,
deleteApp
} = require('../controllers/apps');
router
.route('/')
.post(createApp)
.get(getApps);
router
.route('/:id')
.get(getApp)
.put(updateApp)
.delete(deleteApp);
module.exports = router;

View file

@ -1,13 +1,27 @@
const express = require('express');
const { connectDB } = require('./db');
const errorHandler = require('./middleware/errorHandler');
const colors = require('colors');
require('dotenv').config();
connectDB();
const app = express();
const PORT = process.env.PORT || 5005;
app.get('/', (req, res) => {
res.send('hello');
res.send('Server is working');
})
// Body parser
app.use(express.json());
// Link controllers with routes
app.use('/api/apps', require('./routes/apps'));
// Custom error handler
app.use(errorHandler);
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
console.log(`Server is running on port ${PORT} in ${process.env.NODE_ENV} mode`.yellow.bold);
})

8
utils/ErrorResponse.js Normal file
View file

@ -0,0 +1,8 @@
class ErrorResponse extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode
}
}
module.exports = ErrorResponse;