use standard function for objects to make api more mantainable

This commit is contained in:
hippoz 2020-12-03 00:40:46 +02:00
parent 818cb1afc6
commit bdfdd1a460
5 changed files with 58 additions and 32 deletions

View file

@ -2,12 +2,11 @@ const User = require('../../models/User');
const Category = require('../../models/Category'); const Category = require('../../models/Category');
const Post = require('../../models/Post'); const Post = require('../../models/Post');
const config = require('../../config'); const config = require('../../config');
const secret = require('../../secret');
const { authenticateEndpoint } = require('./authfunctions'); const { authenticateEndpoint } = require('./authfunctions');
const mongoose = require('mongoose'); const mongoose = require('mongoose');
const { body, query, param, validationResult } = require('express-validator'); const { body, param, validationResult } = require('express-validator');
const express = require('express'); const express = require('express');
const app = express.Router(); const app = express.Router();
@ -40,12 +39,7 @@ app.post('/category/create', [
res.status(200).json({ res.status(200).json({
error: false, error: false,
message: 'SUCCESS_CATEGORY_CREATED', message: 'SUCCESS_CATEGORY_CREATED',
category: { category: category.getPublicObject()
title: category.title,
creator: category.creator,
posts: category.posts,
_id: category._id
}
}); });
}, undefined, config.roleMap.USER)); }, undefined, config.roleMap.USER));
@ -104,10 +98,10 @@ app.get('/category/:category/info', [
} }
const categoryId = req.params.category; const categoryId = req.params.category;
const category = await Category.findById(categoryId).populate('posts.creator', 'username _id'); const category = await Category.findById(categoryId).populate('posts.creator', User.getPulicFields());
// TODO: Implement subscribing to a channel and stuff // TODO: Implement subscribing to a channel and stuff
const users = await User.find().sort({ _id: -1 }).limit(50).select('username _id') const users = await User.find().sort({ _id: -1 }).limit(50).select(User.getPulicFields())
if (!category) { if (!category) {
res.status(404).json({ res.status(404).json({
@ -120,12 +114,10 @@ app.get('/category/:category/info', [
res.status(200).json({ res.status(200).json({
error: false, error: false,
message: 'SUCCESS_CATEGORY_DATA_FETCHED', message: 'SUCCESS_CATEGORY_DATA_FETCHED',
category: { category: category.getPublicObject(),
title: category.title, userInfo: {
creator: category.creator, userListLimit: 50,
posts: category.posts, users: users
users: users,
usersListLimit: 50
} }
}); });
})); }));
@ -137,7 +129,7 @@ app.get('/category/list', authenticateEndpoint(async (req, res, user) => {
} }
// TODO: This is probably not efficient // TODO: This is probably not efficient
const categories = await Category.find().sort({ _id: -1 }).limit(count).select('-posts -__v').populate('creator', 'username _id'); const categories = await Category.find().sort({ _id: -1 }).limit(count).select('-posts -__v').populate('creator', User.getPulicFields());
res.status(200).json({ res.status(200).json({
error: false, error: false,

View file

@ -147,17 +147,15 @@ app.post('/token/create', [
}); });
}); });
app.get('/current/info', authenticateEndpoint((req, res, user) => { app.get('/current/info', authenticateEndpoint(async (req, res, user) => {
const userObject = await user.getFullObject();
res.status(200).json({ res.status(200).json({
error: false, error: false,
message: 'SUCCESS_USER_DATA_FETCHED', message: 'SUCCESS_USER_DATA_FETCHED',
user: { user: {
_id: user._id, token: req.cookies.token, // TODO: Passing the token like this is *terribly* insecure
username: user.username, ...userObject
email: user.email,
role: user.role,
permissionLevel: config.roleMap[user.role],
token: req.cookies.token // TODO: Passing the token like this is *terribly* insecure
}, },
}); });
}, undefined, 0)); }, undefined, 0));
@ -184,11 +182,7 @@ app.get('/user/:userid/info', [
res.status(200).json({ res.status(200).json({
error: false, error: false,
message: 'SUCCESS_USER_DATA_FETCHED', message: 'SUCCESS_USER_DATA_FETCHED',
user: { user: await otherUser.getPublicObject(),
_id: otherUser._id,
username: otherUser.username,
role: otherUser.role
},
}); });
})); }));

View file

@ -3,7 +3,7 @@ module.exports = {
mainServerPort: 3000, mainServerPort: 3000,
}, },
address: 'localhost', address: 'localhost',
mongoUrl: 'mongodb://localhost:27017/app', mongoUrl: 'mongodb://192.168.0.105:27017/app',
bcryptRounds: 10, bcryptRounds: 10,
roleMap: { roleMap: {
'BANNED': 0, 'BANNED': 0,

View file

@ -1,10 +1,22 @@
const mongoose = require('mongoose'); const mongoose = require('mongoose');
const Post = require('./Post'); const Post = require('./Post');
const User = require('./User');
const Category = mongoose.model('Category', { const categorySchema = new mongoose.Schema({
title: String, title: String,
creator: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, creator: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
posts: [Post.schema] posts: [Post.schema]
}); });
categorySchema.method('getPublicObject', function() {
return {
title: this.title,
creator: this.populate('creator', User.getPulicFields()).creator,
posts: this.posts,
_id: this._id
}
});
const Category = mongoose.model('Category', categorySchema);
module.exports = Category; module.exports = Category;

View file

@ -1,14 +1,42 @@
const config = require('../config');
const mongoose = require('mongoose'); const mongoose = require('mongoose');
const User = mongoose.model('User', { const userSchema = new mongoose.Schema({
username: String, username: String,
password: String, password: String,
email: String, email: String,
role: String role: String
}); });
userSchema.method('getPublicObject', function() {
return {
username: this.username,
permissionLevel: config.roleMap[this.role],
role: this.role,
_id: this._id
}
});
userSchema.method('getFullObject', function() {
return {
username: this.username,
password: this.password,
email: this.email,
permissionLevel: config.roleMap[this.role],
role: this.role,
_id: this._id
}
});
const User = mongoose.model('User', userSchema);
User.findByUsername = async function(username) { User.findByUsername = async function(username) {
return await User.findOne({ username }).exec(); return await User.findOne({ username }).exec();
}; };
User.getPulicFields = function() {
return 'username role _id';
};
module.exports = User; module.exports = User;