From 4d02572d0c929d36be337c2178081654387cdaf8 Mon Sep 17 00:00:00 2001 From: Filip Rojek Date: Sun, 12 May 2024 12:05:56 +0200 Subject: [PATCH 1/4] Added: API review --- api/src/controllers/reviewController.ts | 52 +++++++++++++++++++++++++ api/src/models/Review.ts | 37 ++++++++++++++++++ api/src/routes/api_v1.ts | 5 ++- api/src/validators/reviewValidator.ts | 45 +++++++++++++++++++++ api/tests/review.test.ts | 49 +++++++++++++++++++++++ 5 files changed, 187 insertions(+), 1 deletion(-) create mode 100644 api/src/controllers/reviewController.ts create mode 100644 api/src/models/Review.ts create mode 100644 api/src/validators/reviewValidator.ts create mode 100644 api/tests/review.test.ts diff --git a/api/src/controllers/reviewController.ts b/api/src/controllers/reviewController.ts new file mode 100644 index 0000000..db0b68d --- /dev/null +++ b/api/src/controllers/reviewController.ts @@ -0,0 +1,52 @@ +import { Request, Response } from 'express'; +import Review from "../models/Review" +import { isValidObjectId, Types } from 'mongoose'; +import {Log} from 'nork' +import Docs from '../services/docsService'; +import { addExam, delExam, IReview } from '../validators/reviewValidator'; + +new Docs('review', 'add', '/api/v1/review/add', 'POST', 'review add api', undefined, addExam, 'status object | review object'); +export async function add_post(req: Request, res: Response) { + try { + const data: IReview = req.body; + const review = new Review(data) + await review.save() + res.status(201).json(Log.info(201, 'review was added', review)) + } catch (err) { + Log.error(500, 'error while adding review', err) + res.status(500).json(Log.error(500, 'something went wrong')) + } +} + +new Docs('review', 'get', '/api/v1/review/get', 'GET', 'review get api', undefined, undefined, 'status object | array of review objects'); +export async function get_get(req: Request, res: Response) { + try { + const review = await Review.find({}, '-__v') + res.status(200).json(Log.info(200, 'reviews fetched', review)) + } catch (err) { + Log.error(500, 'error while geting reviews', err) + res.status(500).json(Log.error(500, 'something went wrong')) + } +} + +new Docs('review', 'del', '/api/v1/review/del', 'POST', 'review del api', undefined, delExam, 'status object'); +export async function del_post(req: Request, res: Response) { + try { + if (!isValidObjectId(req.body._id)) throw Log.error(400, 'this is not valid _id'); + + const review = await Review.deleteOne(new Types.ObjectId(req.body._id)) + + if (review.deletedCount > 0) { + res.status(200).json(Log.info(200, `review ${req.body._id} deleted`)); + return; + } + throw Log.error(400, `review ${req.body._id} does not exist`); + } catch (err: any) { + if (err.code) { + res.status(err.code).json(err); + return; + } + Log.error(500, 'error in del_post', err); + res.status(500).json(Log.error(500, 'something went wrong')); + } +} diff --git a/api/src/models/Review.ts b/api/src/models/Review.ts new file mode 100644 index 0000000..4b1696b --- /dev/null +++ b/api/src/models/Review.ts @@ -0,0 +1,37 @@ +import path from 'path'; +import { Schema, model } from 'mongoose'; +import { IReview } from '../validators/reviewValidator'; + +const schema = new Schema( + { + foam : { + type: Number, + required: true + }, + bitter_sweetness: { + type: Number, + required: true, + }, + taste: { + type: Number, + required: true + }, + packaging: { + type: Number, + required: true + }, + sourness: { + type: Boolean, + required: true + }, + would_again: { + type: Boolean, + required: true + } + }, + { + timestamps: true + } +); + +export default model(path.basename(__filename).split('.')[0], schema); diff --git a/api/src/routes/api_v1.ts b/api/src/routes/api_v1.ts index bedb87f..4e60a18 100644 --- a/api/src/routes/api_v1.ts +++ b/api/src/routes/api_v1.ts @@ -4,6 +4,7 @@ import path from 'path' import * as authController from "../controllers/authController"; import * as beerController from "../controllers/beerController" import * as docsController from "../controllers/docsController" +import * as reviewController from "../controllers/reviewController" import { requireAuth } from "../middlewares/authMiddleware"; import validate from '../middlewares/validateRequest' import valMulter from '../middlewares/validateMulterRequest'; @@ -26,4 +27,6 @@ router.get('/beer/get', [requireAuth], beerController.get_get); router.post('/beer/del', [requireAuth, validate(BVal.del)], beerController.del_post); router.post('/beer/edit', [requireAuth, upload.array('photos', 4), valMulter, validate(BVal.edit)], beerController.edit_post); -export default router; \ No newline at end of file +router.post('/review/add', requireAuth, reviewController.add_post) + +export default router; diff --git a/api/src/validators/reviewValidator.ts b/api/src/validators/reviewValidator.ts new file mode 100644 index 0000000..a458378 --- /dev/null +++ b/api/src/validators/reviewValidator.ts @@ -0,0 +1,45 @@ +import * as yup from 'yup' +import mongoose, { Schema } from 'mongoose' + +interface mongooseAddition { + _id?: Schema.Types.ObjectId; + createdAt?: Schema.Types.Date; + updatedAt?: Schema.Types.Date; +} + +let objectIdSchema = yup.string().test( + 'is-objectId', + 'Invalid ObjectId', + (value: any) => mongoose.Types.ObjectId.isValid(value) +) + +// Add +export const add = yup.object({ + beer_id: objectIdSchema, + foam: yup.number().min(1).max(3).required(), + bitter_sweetness: yup.number().min(1).max(5).required(), + taste: yup.number().min(1).max(5).required(), + packaging: yup.number().min(1).max(5).required(), + sourness: yup.boolean().required(), + would_again: yup.boolean().required() +}) +export interface IReview extends yup.InferType, mongooseAddition {} +export const addExam: IReview = { + beer_id: '6352b303b71cb62222f39895', + foam: 3, + bitter_sweetness: 2, + taste: 5, + packaging: 3, + sourness: false, + would_again: true +} + +// Remove +export const del = yup.object({ + _id: objectIdSchema.required() +}) +export interface IDel extends yup.InferType {} +export const delExam: IDel = { + _id: '6352b303b71cb62222f39895' +}; + diff --git a/api/tests/review.test.ts b/api/tests/review.test.ts new file mode 100644 index 0000000..88b3dee --- /dev/null +++ b/api/tests/review.test.ts @@ -0,0 +1,49 @@ +import supertest from 'supertest'; +import { app } from '../src/app'; +import { login } from './auth.test'; +//import { addExam, delExam, editExam } from '../src/validators/beerValidator'; + +const request = supertest(app); + +describe('POST /api/v1/review/add', () => { + const url = '/api/v1/review/add'; + test('should drop 401 error', async () => { + const res = await request.post(url).send({}); + expect(res.statusCode).toBe(401); + }); + + test('should drop 400 ()', async () => { + const jwt = await login(); + const res = await request.post(url).set('Cookie', jwt).send({}); + + console.log("TEST", await res.body) + + expect(res.statusCode).toBe(400); + }); + +// test('should drop 201', async () => { +// const jwt = await login(); +// const res = await request.post(url).set('Cookie', jwt).send(addExam); +// +// expect(res.statusCode).toBe(201); +// }); +}); + +//describe('GET /api/v1/beer/get', () => { +// const url = '/api/v1/beer/get'; +// +// test('should drop 401', async () => { +// const res = await request.get(url).send(); +// +// expect(res.statusCode).toBe(401); +// }); +// +// test('should drop 200', async () => { +// const jwt = await login(); +// const res = await request.get(url).set('Cookie', jwt).send(); +// +// expect(res.statusCode).toBe(200); +// }); +//}); + + -- 2.45.2 From fa250154720fb6f9e47b0a4cb68889e3477f776a Mon Sep 17 00:00:00 2001 From: Filip Rojek Date: Sun, 12 May 2024 20:02:35 +0200 Subject: [PATCH 2/4] Added: package jest-html-reporter --- api/package.json | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/api/package.json b/api/package.json index ae4c47e..28f181e 100644 --- a/api/package.json +++ b/api/package.json @@ -59,6 +59,7 @@ "eslint": "^8.3.0", "http": "^0.0.1-security", "jest": "^29.7.0", + "jest-html-reporter": "^3.10.2", "mocha": "^9.1.3", "mongodb-memory-server": "^9.2.0", "npm-run-all": "^4.1.5", @@ -76,6 +77,12 @@ "testEnvironment": "node", "setupFilesAfterEnv": [ "./tests/_setupFile.ts" + ], + "reporters": [ + "default", + ["./node_modules/jest-html-reporter", { + "pageTitle": "Test Report" + }] ] } } -- 2.45.2 From bf791db47f2d34ee824cd528b4a6acf224945035 Mon Sep 17 00:00:00 2001 From: Filip Rojek Date: Sun, 12 May 2024 21:25:52 +0200 Subject: [PATCH 3/4] Backend: code formatted --- api/biome.json | 36 ++++ api/src/app.ts | 30 +-- api/src/controllers/authController.ts | 71 ++++--- api/src/controllers/beerController.ts | 87 +++++--- api/src/controllers/docsController.ts | 16 +- api/src/controllers/reviewController.ts | 82 +++++--- api/src/middlewares/authMiddleware.ts | 40 ++-- api/src/middlewares/validateMulterRequest.ts | 10 +- api/src/middlewares/validateRequest.ts | 8 +- api/src/models/Beer.ts | 24 +-- api/src/models/Review.ts | 62 +++--- api/src/models/User.ts | 20 +- api/src/routes/api_v1.ts | 44 ++-- api/src/routes/index.ts | 2 +- api/src/server.ts | 6 +- api/src/services/docsService.ts | 29 ++- api/src/utils/copy_assets.ts | 6 +- api/src/utils/test_mongodb.ts | 8 +- api/src/validators/authValidator.ts | 22 +- api/src/validators/beerValidator.ts | 43 ++-- api/src/validators/reviewValidator.ts | 51 +++-- api/tests/_setupFile.ts | 2 +- api/tests/auth.test.ts | 202 +++++++++---------- api/tests/beer.test.ts | 94 ++++----- api/tests/docs.test.ts | 16 +- api/tests/review.test.ts | 32 ++- 26 files changed, 574 insertions(+), 469 deletions(-) create mode 100644 api/biome.json diff --git a/api/biome.json b/api/biome.json new file mode 100644 index 0000000..d46cb08 --- /dev/null +++ b/api/biome.json @@ -0,0 +1,36 @@ +{ + "$schema": "https://biomejs.dev/schemas/1.7.3/schema.json", + "files": { + "ignore": [".expo/", ".vscode/", "node_modules/", "dist/", "*.json"] + }, + "organizeImports": { + "enabled": true + }, + "linter": { + "enabled": false, + "rules": { + "recommended": true + } + }, + "formatter": { + "enabled": true, + "formatWithErrors": false, + "ignore": [], + "attributePosition": "auto", + "indentStyle": "tab", + "indentWidth": 2, + "lineEnding": "lf", + "lineWidth": 120 + }, + "javascript": { + "formatter": { + "arrowParentheses": "always", + "bracketSameLine": true, + "bracketSpacing": true, + "jsxQuoteStyle": "double", + "quoteProperties": "asNeeded", + "semicolons": "always", + "trailingComma": "all" + } + } +} diff --git a/api/src/app.ts b/api/src/app.ts index 17d7e83..ee9eb77 100644 --- a/api/src/app.ts +++ b/api/src/app.ts @@ -1,29 +1,29 @@ import express from "express"; import morgan from "morgan"; -import path from 'path' -import cors from 'cors' -import cookieParser from 'cookie-parser' +import path from "path"; +import cors from "cors"; +import cookieParser from "cookie-parser"; import { router as routes } from "./routes"; //import { router as middlewares } from './middlewares' -import env from './config/environment' +import env from "./config/environment"; -export let corsWhitelist: Array -if (env.CORS_WHITELIST != 'undefined') { - corsWhitelist = [...['http://localhost:8080', 'http://localhost:6040'], ...env.CORS_WHITELIST.split(';')] +export let corsWhitelist: Array; +if (env.CORS_WHITELIST != "undefined") { + corsWhitelist = [...["http://localhost:8080", "http://localhost:6040"], ...env.CORS_WHITELIST.split(";")]; } else { - corsWhitelist = ['http://localhost:8080', 'http://localhost:6040'] + corsWhitelist = ["http://localhost:8080", "http://localhost:6040"]; } const corsOptions = { origin: function (origin: any, callback: any) { if (!origin || corsWhitelist.indexOf(origin) !== -1) { - callback(null, true) + callback(null, true); } else { - callback(new Error('Not allowed by CORS')) + callback(new Error("Not allowed by CORS")); } }, optionsSuccessStatus: 200, - credentials: true -} + credentials: true, +}; export const app = express(); @@ -31,12 +31,12 @@ export const app = express(); //app.use(middlewares) //app.set('view engine', 'ejs') //app.set('views', path.join(__dirname, 'views')) -app.use(cors(corsOptions)) +app.use(cors(corsOptions)); app.use(morgan("dev")); app.use(express.urlencoded({ extended: true })); app.use(express.json()); -app.use(express.static(path.join(__dirname, 'public'))) -app.use(cookieParser()) +app.use(express.static(path.join(__dirname, "public"))); +app.use(cookieParser()); // Routes app.use(routes); diff --git a/api/src/controllers/authController.ts b/api/src/controllers/authController.ts index 7e33dad..42b5c2f 100644 --- a/api/src/controllers/authController.ts +++ b/api/src/controllers/authController.ts @@ -1,13 +1,13 @@ -import { Request, Response } from 'express'; -import bcrypt from 'bcrypt'; -import jwt from 'jsonwebtoken'; -import env from '../config/environment'; -import Docs from '../services/docsService'; -import User from '../models/User'; -import {Log} from 'nork' -import { IUser, signupExam, ISignin, signinExam } from '../validators/authValidator'; +import { Request, Response } from "express"; +import bcrypt from "bcrypt"; +import jwt from "jsonwebtoken"; +import env from "../config/environment"; +import Docs from "../services/docsService"; +import User from "../models/User"; +import { Log } from "nork"; +import { IUser, signupExam, ISignin, signinExam } from "../validators/authValidator"; -new Docs('user', 'signup', '/api/v1/auth/signup', 'POST', 'user signup api', undefined, signupExam, 'status object'); +new Docs("user", "signup", "/api/v1/auth/signup", "POST", "user signup api", undefined, signupExam, "status object"); export async function signup_post(req: Request, res: Response) { try { const payload: IUser = req.body; @@ -16,27 +16,27 @@ export async function signup_post(req: Request, res: Response) { const user = new User(payload); await user.save(); - res.status(201).json(Log.info(201, 'user was successfully signed up')); + res.status(201).json(Log.info(201, "user was successfully signed up")); } catch (err: any) { if (err.code == 11000) { - res.status(400).json(Log.error(400, 'this user already exists')); + res.status(400).json(Log.error(400, "this user already exists")); return; } Log.error(500, err); - res.status(500).json(Log.error(500, 'something went wrong')); + res.status(500).json(Log.error(500, "something went wrong")); } } -new Docs('user', 'signin', '/api/v1/auth/signin', 'POST', 'user signin api', undefined, signinExam, 'status object'); +new Docs("user", "signin", "/api/v1/auth/signin", "POST", "user signin api", undefined, signinExam, "status object"); export async function signin_post(req: Request, res: Response) { try { const payload: ISignin = req.body; const user = await User.findOne({ email: payload.email }); if (!user) { - res.cookie('jwt', '', { httpOnly: true, maxAge: 0 }); - res.cookie('auth', false, { httpOnly: false, maxAge: 0 }); - res.status(401).json(Log.error(401, 'email or password is wrong')); + res.cookie("jwt", "", { httpOnly: true, maxAge: 0 }); + res.cookie("auth", false, { httpOnly: false, maxAge: 0 }); + res.status(401).json(Log.error(401, "email or password is wrong")); return; } @@ -44,38 +44,47 @@ export async function signin_post(req: Request, res: Response) { const maxAge = 3 * 24 * 60 * 60; // 3 days in seconds const createToken = (id: any) => { return jwt.sign({ id }, env.JWT_SECRET, { - expiresIn: maxAge + expiresIn: maxAge, }); }; const token = createToken(user._id); - res.cookie('jwt', token, { httpOnly: true, maxAge: maxAge * 1000 }); - res.cookie('auth', true, { httpOnly: false, maxAge: maxAge * 1000 }); + res.cookie("jwt", token, { httpOnly: true, maxAge: maxAge * 1000 }); + res.cookie("auth", true, { httpOnly: false, maxAge: maxAge * 1000 }); - res.json(Log.info(200, 'user is logged in', {jwt: token})); + res.json(Log.info(200, "user is logged in", { jwt: token })); return; } - res.cookie('jwt', '', { httpOnly: true, maxAge: 0 }); - res.cookie('auth', false, { httpOnly: false, maxAge: 0 }); - res.status(401).json(Log.error(401, 'email or password is wrong')); + res.cookie("jwt", "", { httpOnly: true, maxAge: 0 }); + res.cookie("auth", false, { httpOnly: false, maxAge: 0 }); + res.status(401).json(Log.error(401, "email or password is wrong")); } catch (err: any) { Log.error(500, err); - res.status(500).json(Log.error(500, 'something went wrong')); + res.status(500).json(Log.error(500, "something went wrong")); } } -new Docs('user', 'logout', '/api/v1/auth/logout', 'POST', 'user logout api', undefined, {}, 'status object'); +new Docs("user", "logout", "/api/v1/auth/logout", "POST", "user logout api", undefined, {}, "status object"); export function logout_post(req: Request, res: Response) { - res.cookie('jwt', '', { httpOnly: true, maxAge: 0 }); - res.cookie('auth', false, { httpOnly: false, maxAge: 0 }); - res.json(Log.info(200, 'user was logged out')); + res.cookie("jwt", "", { httpOnly: true, maxAge: 0 }); + res.cookie("auth", false, { httpOnly: false, maxAge: 0 }); + res.json(Log.info(200, "user was logged out")); } -new Docs('user', 'status', '/api/v1/auth/status', 'GET', 'user login status api', undefined, undefined, 'status code | user object'); +new Docs( + "user", + "status", + "/api/v1/auth/status", + "GET", + "user login status api", + undefined, + undefined, + "status code | user object", +); export function status_get(req: Request, res: Response) { let userObject = res.locals.user; userObject.password = undefined; userObject.__v = undefined; - res.status(200).json(Log.info(200, 'user is logged in', userObject)); -} \ No newline at end of file + res.status(200).json(Log.info(200, "user is logged in", userObject)); +} diff --git a/api/src/controllers/beerController.ts b/api/src/controllers/beerController.ts index be3ba06..ce21c44 100644 --- a/api/src/controllers/beerController.ts +++ b/api/src/controllers/beerController.ts @@ -1,13 +1,22 @@ -import { Request, Response } from 'express'; -import Beer from '../models/Beer'; -import { isValidObjectId, Types } from 'mongoose'; -import fs from 'fs'; -import path from 'path'; -import {Log} from 'nork' -import Docs from '../services/docsService'; -import { addExam, delExam, editExam, IBeer } from '../validators/beerValidator'; +import { Request, Response } from "express"; +import Beer from "../models/Beer"; +import { isValidObjectId, Types } from "mongoose"; +import fs from "fs"; +import path from "path"; +import { Log } from "nork"; +import Docs from "../services/docsService"; +import { addExam, delExam, editExam, IBeer } from "../validators/beerValidator"; -new Docs('beer', 'add', '/api/v1/beer/add', 'POST', 'beer add api', undefined, { ...addExam, photos: 'optional field | max 4 images | formData' }, 'status object | beer object'); +new Docs( + "beer", + "add", + "/api/v1/beer/add", + "POST", + "beer add api", + undefined, + { ...addExam, photos: "optional field | max 4 images | formData" }, + "status object | beer object", +); export async function add_post(req: Request, res: Response) { try { if (req.files) { @@ -19,28 +28,37 @@ export async function add_post(req: Request, res: Response) { } const beer = new Beer(req.body); await beer.save(); - res.status(201).json(Log.info(201, 'beer was created', beer)); + res.status(201).json(Log.info(201, "beer was created", beer)); } catch (err: any) { - Log.error(500, 'error in add_post', err); - res.status(500).json(Log.error(500, 'something went wrong')); + Log.error(500, "error in add_post", err); + res.status(500).json(Log.error(500, "something went wrong")); } } -new Docs('beer', 'get', '/api/v1/beer/get', 'GET', 'beer get api', undefined, undefined, 'status object | array of beer objects'); +new Docs( + "beer", + "get", + "/api/v1/beer/get", + "GET", + "beer get api", + undefined, + undefined, + "status object | array of beer objects", +); export async function get_get(req: Request, res: Response) { try { - const beer = await Beer.find({}, '-__v'); - res.status(200).json(Log.info(200, 'beers fetched', beer)); + const beer = await Beer.find({}, "-__v"); + res.status(200).json(Log.info(200, "beers fetched", beer)); } catch (err: any) { - Log.error(500, 'error in get_get', err); - res.status(500).json(Log.error(500, 'something went wrong')); + Log.error(500, "error in get_get", err); + res.status(500).json(Log.error(500, "something went wrong")); } } -new Docs('beer', 'del', '/api/v1/beer/del', 'POST', 'beer del api', undefined, delExam, 'status object'); +new Docs("beer", "del", "/api/v1/beer/del", "POST", "beer del api", undefined, delExam, "status object"); export async function del_post(req: Request, res: Response) { try { - if (!isValidObjectId(req.body._id)) throw Log.error(400, 'this is not valid _id'); + if (!isValidObjectId(req.body._id)) throw Log.error(400, "this is not valid _id"); const beer = await Beer.deleteOne(new Types.ObjectId(req.body._id)); @@ -54,30 +72,39 @@ export async function del_post(req: Request, res: Response) { res.status(err.code).json(err); return; } - Log.error(500, 'error in del_post', err); - res.status(500).json(Log.error(500, 'something went wrong')); + Log.error(500, "error in del_post", err); + res.status(500).json(Log.error(500, "something went wrong")); } } -new Docs('beer', 'edit', '/api/v1/beer/edit', 'POST', 'beer edit api', undefined, { ...editExam, photos: 'optional field | max 4 images | formData' }, 'status object | beer data'); +new Docs( + "beer", + "edit", + "/api/v1/beer/edit", + "POST", + "beer edit api", + undefined, + { ...editExam, photos: "optional field | max 4 images | formData" }, + "status object | beer data", +); export async function edit_post(req: Request, res: Response) { try { - if (!isValidObjectId(req.body._id)) throw Log.error(400, 'this is not valid _id'); + if (!isValidObjectId(req.body._id)) throw Log.error(400, "this is not valid _id"); if (req.files) { if (!req.body.imgs) { req.body.imgs = []; } - if (typeof req.body.imgs == 'string') { + if (typeof req.body.imgs == "string") { req.body.imgs = [req.body.imgs]; } if (req.body.imgs.length + req.files.length > 4) { req.body.imgs.forEach((el: string[]) => { - fs.rmSync(path.join(__dirname, '../../uploads/' + el)); + fs.rmSync(path.join(__dirname, "../../uploads/" + el)); }); - throw Log.error(400, 'exceeds the 4 image limit'); + throw Log.error(400, "exceeds the 4 image limit"); } const files: any = req.files; @@ -90,11 +117,11 @@ export async function edit_post(req: Request, res: Response) { const beer = await Beer.findOneAndUpdate(new Types.ObjectId(req.body._id), payload, { new: true }); res.json(Log.info(200, `beer ${req.body._id} edited`, beer)); } catch (err: any) { - if (err.code && typeof err.code == 'number') { + if (err.code && typeof err.code == "number") { res.status(err.code).json(err); return; } - Log.error(500, 'error in del_post', err); - res.status(500).json(Log.error(500, 'something went wrong')); + Log.error(500, "error in del_post", err); + res.status(500).json(Log.error(500, "something went wrong")); } -} \ No newline at end of file +} diff --git a/api/src/controllers/docsController.ts b/api/src/controllers/docsController.ts index 33bf0f8..0325aa9 100644 --- a/api/src/controllers/docsController.ts +++ b/api/src/controllers/docsController.ts @@ -1,14 +1,14 @@ -import { Request, Response } from 'express'; -import path from 'path'; -import fs from 'fs'; -import {Log} from 'nork' -import { Docs } from '../services/docsService'; +import { Request, Response } from "express"; +import path from "path"; +import fs from "fs"; +import { Log } from "nork"; +import { Docs } from "../services/docsService"; -new Docs('docs', 'get_all', '/api/v1', 'GET', 'Get docs json', undefined, undefined, 'docs json'); +new Docs("docs", "get_all", "/api/v1", "GET", "Get docs json", undefined, undefined, "docs json"); export function docs_get(req: Request, res: Response) { try { - res.json(JSON.parse(fs.readFileSync(path.join(__dirname, '../public/api.json')).toString())); + res.json(JSON.parse(fs.readFileSync(path.join(__dirname, "../public/api.json")).toString())); } catch (err: any) { - res.status(500).json(Log.error(500, 'api.json docs file does not exists under public folder')); + res.status(500).json(Log.error(500, "api.json docs file does not exists under public folder")); } } diff --git a/api/src/controllers/reviewController.ts b/api/src/controllers/reviewController.ts index db0b68d..6104e23 100644 --- a/api/src/controllers/reviewController.ts +++ b/api/src/controllers/reviewController.ts @@ -1,52 +1,70 @@ -import { Request, Response } from 'express'; -import Review from "../models/Review" -import { isValidObjectId, Types } from 'mongoose'; -import {Log} from 'nork' -import Docs from '../services/docsService'; -import { addExam, delExam, IReview } from '../validators/reviewValidator'; +import { Request, Response } from "express"; +import Review from "../models/Review"; +import { isValidObjectId, Types } from "mongoose"; +import { Log } from "nork"; +import Docs from "../services/docsService"; +import { addExam, delExam, IReview } from "../validators/reviewValidator"; -new Docs('review', 'add', '/api/v1/review/add', 'POST', 'review add api', undefined, addExam, 'status object | review object'); +new Docs( + "review", + "add", + "/api/v1/review/add", + "POST", + "review add api", + undefined, + addExam, + "status object | review object", +); export async function add_post(req: Request, res: Response) { - try { - const data: IReview = req.body; - const review = new Review(data) - await review.save() - res.status(201).json(Log.info(201, 'review was added', review)) - } catch (err) { - Log.error(500, 'error while adding review', err) - res.status(500).json(Log.error(500, 'something went wrong')) - } + try { + const data: IReview = req.body; + const review = new Review(data); + await review.save(); + res.status(201).json(Log.info(201, "review was added", review)); + } catch (err) { + Log.error(500, "error while adding review", err); + res.status(500).json(Log.error(500, "something went wrong")); + } } -new Docs('review', 'get', '/api/v1/review/get', 'GET', 'review get api', undefined, undefined, 'status object | array of review objects'); +new Docs( + "review", + "get", + "/api/v1/review/get", + "GET", + "review get api", + undefined, + undefined, + "status object | array of review objects", +); export async function get_get(req: Request, res: Response) { - try { - const review = await Review.find({}, '-__v') - res.status(200).json(Log.info(200, 'reviews fetched', review)) - } catch (err) { - Log.error(500, 'error while geting reviews', err) - res.status(500).json(Log.error(500, 'something went wrong')) - } + try { + const review = await Review.find({}, "-__v"); + res.status(200).json(Log.info(200, "reviews fetched", review)); + } catch (err) { + Log.error(500, "error while geting reviews", err); + res.status(500).json(Log.error(500, "something went wrong")); + } } -new Docs('review', 'del', '/api/v1/review/del', 'POST', 'review del api', undefined, delExam, 'status object'); +new Docs("review", "del", "/api/v1/review/del", "POST", "review del api", undefined, delExam, "status object"); export async function del_post(req: Request, res: Response) { - try { - if (!isValidObjectId(req.body._id)) throw Log.error(400, 'this is not valid _id'); + try { + if (!isValidObjectId(req.body._id)) throw Log.error(400, "this is not valid _id"); - const review = await Review.deleteOne(new Types.ObjectId(req.body._id)) + const review = await Review.deleteOne(new Types.ObjectId(req.body._id)); if (review.deletedCount > 0) { res.status(200).json(Log.info(200, `review ${req.body._id} deleted`)); return; } throw Log.error(400, `review ${req.body._id} does not exist`); - } catch (err: any) { + } catch (err: any) { if (err.code) { res.status(err.code).json(err); return; } - Log.error(500, 'error in del_post', err); - res.status(500).json(Log.error(500, 'something went wrong')); - } + Log.error(500, "error in del_post", err); + res.status(500).json(Log.error(500, "something went wrong")); + } } diff --git a/api/src/middlewares/authMiddleware.ts b/api/src/middlewares/authMiddleware.ts index 475f177..4d65802 100644 --- a/api/src/middlewares/authMiddleware.ts +++ b/api/src/middlewares/authMiddleware.ts @@ -1,9 +1,9 @@ -import { Request, Response, NextFunction } from 'express'; -import jwt from 'jsonwebtoken'; -import env from '../config/environment'; -import { Log } from 'nork'; -import User from '../models/User'; -import { isValidObjectId } from 'mongoose'; +import { Request, Response, NextFunction } from "express"; +import jwt from "jsonwebtoken"; +import env from "../config/environment"; +import { Log } from "nork"; +import User from "../models/User"; +import { isValidObjectId } from "mongoose"; export function requireAuth(req: Request, res: Response, next: NextFunction) { const token = req.cookies?.jwt; @@ -12,40 +12,40 @@ export function requireAuth(req: Request, res: Response, next: NextFunction) { jwt.verify(token, env.JWT_SECRET, async (err: any, decodedToken: any) => { if (err) { // console.error(err.message) - res.status(401).send(Log.error(401, 'user is not authenticated')); + res.status(401).send(Log.error(401, "user is not authenticated")); } if (!err) { const user = await User.findById(decodedToken.id); if (user === null) { - res.status(401).send(Log.error(401, 'user is not authenticated')); + res.status(401).send(Log.error(401, "user is not authenticated")); return; } res.locals.user = user; - Log.info(100, 'user is authenticated'); + Log.info(100, "user is authenticated"); next(); } }); } if (!token) { - res.status(401).send(Log.error(401, 'user is not authenticated')); + res.status(401).send(Log.error(401, "user is not authenticated")); } } export function requireVerified(req: Request, res: Response, next: NextFunction) { if (res.locals.user._id) { if (res.locals.user.verified) { - Log.info(100, 'user is verified'); + Log.info(100, "user is verified"); next(); return; } - res.status(403).json(Log.error(403, 'user is not verified')); + res.status(403).json(Log.error(403, "user is not verified")); return; } if (!res.locals.user._id) { - res.status(401).send(Log.error(401, 'user is not authenticated')); + res.status(401).send(Log.error(401, "user is not authenticated")); return; } } @@ -53,33 +53,33 @@ export function requireVerified(req: Request, res: Response, next: NextFunction) export class requireRole { static Admin(req: Request, res: Response, next: NextFunction) { if (res.locals.user.admin) { - Log.info(100, 'user is admin'); + Log.info(100, "user is admin"); next(); return; } - res.status(403).json(Log.error(403, 'insufficient permissions')); + res.status(403).json(Log.error(403, "insufficient permissions")); return; } static Owner(req: Request, res: Response, next: NextFunction) { try { if (!isValidObjectId(req.body.domain_id)) { - throw Log.error(400, 'neznámé domain_id'); + throw Log.error(400, "neznámé domain_id"); } const domain = res.locals.user.domains.filter((domain: any) => domain.domain_id == req.body.domain_id); console.log(domain); if (domain.length < 1) { - throw Log.error(400, 'neznámé domain_id'); + throw Log.error(400, "neznámé domain_id"); } if (domain[0].role == 1) { - Log.info(100, 'user is owner'); + Log.info(100, "user is owner"); next(); return; } - res.status(403).json(Log.error(403, 'insufficient permissions')); + res.status(403).json(Log.error(403, "insufficient permissions")); return; } catch (err: any) { res.status(400).json(err); @@ -87,4 +87,4 @@ export class requireRole { } static Editor(req: Request, res: Response, next: NextFunction) {} static Guest(req: Request, res: Response, next: NextFunction) {} -} \ No newline at end of file +} diff --git a/api/src/middlewares/validateMulterRequest.ts b/api/src/middlewares/validateMulterRequest.ts index 6f7babd..d4f2a41 100644 --- a/api/src/middlewares/validateMulterRequest.ts +++ b/api/src/middlewares/validateMulterRequest.ts @@ -1,11 +1,11 @@ -import multer from 'multer'; -import {Log} from 'nork' -import { Request, Response, NextFunction } from 'express'; +import multer from "multer"; +import { Log } from "nork"; +import { Request, Response, NextFunction } from "express"; const validateMulterRequestMiddleware = async (err: any, req: Request, res: Response, next: NextFunction) => { if (err instanceof multer.MulterError) { - Log.error(500, 'error while processing uploaded files', JSON.stringify(err)); - res.status(400).json(Log.error(400, 'error while processing uploaded files')); + Log.error(500, "error while processing uploaded files", JSON.stringify(err)); + res.status(400).json(Log.error(400, "error while processing uploaded files")); return; } else { next(); diff --git a/api/src/middlewares/validateRequest.ts b/api/src/middlewares/validateRequest.ts index d879a04..8caa445 100644 --- a/api/src/middlewares/validateRequest.ts +++ b/api/src/middlewares/validateRequest.ts @@ -1,6 +1,6 @@ -import { Request, Response, NextFunction } from 'express'; -import { object, AnySchema } from 'yup'; -import { Log } from 'nork'; +import { Request, Response, NextFunction } from "express"; +import { object, AnySchema } from "yup"; +import { Log } from "nork"; const validate = (schema: AnySchema) => async (req: Request, res: Response, next: NextFunction) => { try { @@ -8,7 +8,7 @@ const validate = (schema: AnySchema) => async (req: Request, res: Response, next next(); } catch (err: any) { - return res.status(400).json(Log.error(400, 'validation error', err)); + return res.status(400).json(Log.error(400, "validation error", err)); } }; diff --git a/api/src/models/Beer.ts b/api/src/models/Beer.ts index 6710a3a..84079a3 100644 --- a/api/src/models/Beer.ts +++ b/api/src/models/Beer.ts @@ -1,34 +1,34 @@ -import path from 'path'; -import { Schema, model } from 'mongoose'; -import { IBeer } from '../validators/beerValidator'; +import path from "path"; +import { Schema, model } from "mongoose"; +import { IBeer } from "../validators/beerValidator"; const schema = new Schema( { name: { type: String, - required: true + required: true, }, degree: { type: Number, - required: true + required: true, }, packaging: { type: String, - required: true + required: true, }, brand: { type: String, - required: true + required: true, }, imgs: { type: Array, required: false, - default: [] - } + default: [], + }, }, { - timestamps: true - } + timestamps: true, + }, ); -export default model(path.basename(__filename).split('.')[0], schema); \ No newline at end of file +export default model(path.basename(__filename).split(".")[0], schema); diff --git a/api/src/models/Review.ts b/api/src/models/Review.ts index 4b1696b..f9a4fcf 100644 --- a/api/src/models/Review.ts +++ b/api/src/models/Review.ts @@ -1,37 +1,37 @@ -import path from 'path'; -import { Schema, model } from 'mongoose'; -import { IReview } from '../validators/reviewValidator'; +import path from "path"; +import { Schema, model } from "mongoose"; +import { IReview } from "../validators/reviewValidator"; const schema = new Schema( { - foam : { - type: Number, - required: true - }, - bitter_sweetness: { - type: Number, - required: true, - }, - taste: { - type: Number, - required: true - }, - packaging: { - type: Number, - required: true - }, - sourness: { - type: Boolean, - required: true - }, - would_again: { - type: Boolean, - required: true - } - }, + foam: { + type: Number, + required: true, + }, + bitter_sweetness: { + type: Number, + required: true, + }, + taste: { + type: Number, + required: true, + }, + packaging: { + type: Number, + required: true, + }, + sourness: { + type: Boolean, + required: true, + }, + would_again: { + type: Boolean, + required: true, + }, + }, { - timestamps: true - } + timestamps: true, + }, ); -export default model(path.basename(__filename).split('.')[0], schema); +export default model(path.basename(__filename).split(".")[0], schema); diff --git a/api/src/models/User.ts b/api/src/models/User.ts index 9f0a3ae..17ef5a2 100644 --- a/api/src/models/User.ts +++ b/api/src/models/User.ts @@ -1,26 +1,26 @@ -import path from 'path'; -import { Schema, model } from 'mongoose'; -import { IUser } from '../validators/authValidator'; +import path from "path"; +import { Schema, model } from "mongoose"; +import { IUser } from "../validators/authValidator"; const schema = new Schema( { username: { type: String, - required: true + required: true, }, email: { type: String, required: true, - unique: true + unique: true, }, password: { type: String, - required: true - } + required: true, + }, }, { - timestamps: true - } + timestamps: true, + }, ); -export default model(path.basename(__filename).split('.')[0], schema); +export default model(path.basename(__filename).split(".")[0], schema); diff --git a/api/src/routes/api_v1.ts b/api/src/routes/api_v1.ts index 4e60a18..f05be66 100644 --- a/api/src/routes/api_v1.ts +++ b/api/src/routes/api_v1.ts @@ -1,32 +1,40 @@ import { Router } from "express"; -import multer from 'multer'; -import path from 'path' +import multer from "multer"; +import path from "path"; import * as authController from "../controllers/authController"; -import * as beerController from "../controllers/beerController" -import * as docsController from "../controllers/docsController" -import * as reviewController from "../controllers/reviewController" +import * as beerController from "../controllers/beerController"; +import * as docsController from "../controllers/docsController"; +import * as reviewController from "../controllers/reviewController"; import { requireAuth } from "../middlewares/authMiddleware"; -import validate from '../middlewares/validateRequest' -import valMulter from '../middlewares/validateMulterRequest'; -import * as AuthVal from '../validators/authValidator' -import * as BVal from '../validators/beerValidator'; +import validate from "../middlewares/validateRequest"; +import valMulter from "../middlewares/validateMulterRequest"; +import * as AuthVal from "../validators/authValidator"; +import * as BVal from "../validators/beerValidator"; -const upload = multer({ dest: path.resolve(__dirname, '../../uploads') }); +const upload = multer({ dest: path.resolve(__dirname, "../../uploads") }); const router = Router(); -router.get('/', docsController.docs_get); +router.get("/", docsController.docs_get); -router.post("/auth/signup",validate(AuthVal.signup) , authController.signup_post); -router.post("/auth/signin",validate(AuthVal.signin) , authController.signin_post); +router.post("/auth/signup", validate(AuthVal.signup), authController.signup_post); +router.post("/auth/signin", validate(AuthVal.signin), authController.signin_post); router.post("/auth/logout", requireAuth, authController.logout_post); router.get("/auth/status", requireAuth, authController.status_get); -router.post('/beer/add', [requireAuth, upload.array('photos', 4), valMulter, validate(BVal.add)], beerController.add_post); -router.get('/beer/get', [requireAuth], beerController.get_get); -router.post('/beer/del', [requireAuth, validate(BVal.del)], beerController.del_post); -router.post('/beer/edit', [requireAuth, upload.array('photos', 4), valMulter, validate(BVal.edit)], beerController.edit_post); +router.post( + "/beer/add", + [requireAuth, upload.array("photos", 4), valMulter, validate(BVal.add)], + beerController.add_post, +); +router.get("/beer/get", [requireAuth], beerController.get_get); +router.post("/beer/del", [requireAuth, validate(BVal.del)], beerController.del_post); +router.post( + "/beer/edit", + [requireAuth, upload.array("photos", 4), valMulter, validate(BVal.edit)], + beerController.edit_post, +); -router.post('/review/add', requireAuth, reviewController.add_post) +router.post("/review/add", requireAuth, reviewController.add_post); export default router; diff --git a/api/src/routes/index.ts b/api/src/routes/index.ts index 05b7ef8..f81dee8 100644 --- a/api/src/routes/index.ts +++ b/api/src/routes/index.ts @@ -11,5 +11,5 @@ router.use("/api/v1", api_v1); // 404 router.use((req: Request, res: Response) => { - res.status(404).send("Error 404\n"); + res.status(404).send("Error 404\n"); }); diff --git a/api/src/server.ts b/api/src/server.ts index aac0ef0..2e0457e 100644 --- a/api/src/server.ts +++ b/api/src/server.ts @@ -1,7 +1,7 @@ import http from "http"; import { app } from "./app"; import env from "./config/environment"; -import mongoose from 'mongoose' // TODO: dopsat nork module pro db +import mongoose from "mongoose"; // TODO: dopsat nork module pro db import { Log } from "nork"; const port: number = env.APP_PORT || 8080; @@ -23,13 +23,11 @@ export const server = http.createServer(app); // runServer() //} - - (async () => { if (!process.env.DOCS_GEN) { try { await mongoose.connect(env.DB_URI); - Log.info(200, 'connected to db'); + Log.info(200, "connected to db"); server.listen(port, () => { Log.info(200, `Server is listening on http://localhost:${port}`); }); diff --git a/api/src/services/docsService.ts b/api/src/services/docsService.ts index a10c744..1df7c0d 100644 --- a/api/src/services/docsService.ts +++ b/api/src/services/docsService.ts @@ -1,8 +1,8 @@ -import fs from 'fs'; -import path from 'path'; +import fs from "fs"; +import path from "path"; -export type HttpMethods = 'POST' | 'GET' | 'PUT' | 'DELETE'; -export type ApiResponse = 'status object' | Object | string; +export type HttpMethods = "POST" | "GET" | "PUT" | "DELETE"; +export type ApiResponse = "status object" | Object | string; export class Docs { private name: string; @@ -14,7 +14,16 @@ export class Docs { private body?: Object; private response?: ApiResponse; - public constructor(name: string, operation: string, route: string, method: HttpMethods, description?: string, parameters?: Object[], body?: Object, response?: ApiResponse) { + public constructor( + name: string, + operation: string, + route: string, + method: HttpMethods, + description?: string, + parameters?: Object[], + body?: Object, + response?: ApiResponse, + ) { this.name = name; this.operation = operation; this.route = route; @@ -32,14 +41,14 @@ export class Docs { return false; } - const jsonPath = path.join(__dirname, '../public/api.json'); - const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, '../../package.json')).toString()); + const jsonPath = path.join(__dirname, "../public/api.json"); + const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, "../../package.json")).toString()); const jsonAPI = () => JSON.parse(fs.readFileSync(jsonPath).toString()); const genJsonAPI = () => fs.writeFileSync(jsonPath, JSON.stringify({ version: pkg.version, endpoints: {} })); - if (!fs.existsSync(path.join(__dirname, '../public'))) { - fs.mkdirSync(path.join(__dirname, '../public')); + if (!fs.existsSync(path.join(__dirname, "../public"))) { + fs.mkdirSync(path.join(__dirname, "../public")); } if (!fs.existsSync(jsonPath)) { @@ -59,4 +68,4 @@ export class Docs { } } -export default Docs; \ No newline at end of file +export default Docs; diff --git a/api/src/utils/copy_assets.ts b/api/src/utils/copy_assets.ts index 33bcc40..a84dfbf 100644 --- a/api/src/utils/copy_assets.ts +++ b/api/src/utils/copy_assets.ts @@ -1,6 +1,6 @@ -import * as shell from 'shelljs'; +import * as shell from "shelljs"; // Copy all the view templates //shell.cp('-R', 'src/views', 'dist/') -shell.cp('-R', 'src/public', 'dist/'); -shell.cp('-u', 'src/.env', 'dist/'); +shell.cp("-R", "src/public", "dist/"); +shell.cp("-u", "src/.env", "dist/"); diff --git a/api/src/utils/test_mongodb.ts b/api/src/utils/test_mongodb.ts index 3e0b35e..0170b21 100644 --- a/api/src/utils/test_mongodb.ts +++ b/api/src/utils/test_mongodb.ts @@ -1,10 +1,10 @@ -const mongoose = require('mongoose'); -const { MongoMemoryServer } = require('mongodb-memory-server'); +const mongoose = require("mongoose"); +const { MongoMemoryServer } = require("mongodb-memory-server"); let mongo: any = null; const connectDB = async () => { - mongo = await MongoMemoryServer.create({ binary: { os: { os: 'linux', dist: 'ubuntu', release: '18.04' } } }); // TODO: check that host OS is Void Linux, else remove the argument + mongo = await MongoMemoryServer.create({ binary: { os: { os: "linux", dist: "ubuntu", release: "18.04" } } }); // TODO: check that host OS is Void Linux, else remove the argument const uri = mongo.getUri(); await mongoose.connect(uri); @@ -27,4 +27,4 @@ const dropCollections = async () => { } }; -export { connectDB, dropDB, dropCollections }; \ No newline at end of file +export { connectDB, dropDB, dropCollections }; diff --git a/api/src/validators/authValidator.ts b/api/src/validators/authValidator.ts index 0b49f76..77fd9e6 100644 --- a/api/src/validators/authValidator.ts +++ b/api/src/validators/authValidator.ts @@ -1,7 +1,7 @@ -import * as yup from 'yup'; -import YupPassword from 'yup-password'; +import * as yup from "yup"; +import YupPassword from "yup-password"; YupPassword(yup); -import { Schema } from 'mongoose'; +import { Schema } from "mongoose"; interface mongooseAddition { _id?: Schema.Types.ObjectId; @@ -13,22 +13,22 @@ interface mongooseAddition { export const signup = yup.object({ username: yup.string().required(), email: yup.string().email().required(), - password: yup.string().min(8).minLowercase(1).minUppercase(1).minNumbers(1).required() + password: yup.string().min(8).minLowercase(1).minUppercase(1).minNumbers(1).required(), }); export interface IUser extends yup.InferType, mongooseAddition {} export const signupExam: IUser = { - username: 'testuser', - email: 'text@example.com', - password: 'Test1234' + username: "testuser", + email: "text@example.com", + password: "Test1234", }; // SignIn export const signin = yup.object({ email: yup.string().email().required(), - password: yup.string().min(8).minLowercase(1).minUppercase(1).minNumbers(1).required() + password: yup.string().min(8).minLowercase(1).minUppercase(1).minNumbers(1).required(), }); export interface ISignin extends yup.InferType, mongooseAddition {} export const signinExam: ISignin = { - email: 'text@example.com', - password: 'Test1234' -}; \ No newline at end of file + email: "text@example.com", + password: "Test1234", +}; diff --git a/api/src/validators/beerValidator.ts b/api/src/validators/beerValidator.ts index 183e353..d4113dd 100644 --- a/api/src/validators/beerValidator.ts +++ b/api/src/validators/beerValidator.ts @@ -1,7 +1,7 @@ -import * as yup from 'yup'; -import YupPassword from 'yup-password'; +import * as yup from "yup"; +import YupPassword from "yup-password"; YupPassword(yup); -import { Schema } from 'mongoose'; +import { Schema } from "mongoose"; interface mongooseAddition { _id?: Schema.Types.ObjectId; @@ -14,23 +14,23 @@ export const add = yup.object({ brand: yup.string().required(), name: yup.string().required(), degree: yup.number().required(), - packaging: yup.string().required() + packaging: yup.string().required(), }); export interface IBeer extends yup.InferType, mongooseAddition {} export const addExam: IBeer = { - brand: 'Pilsner Urqell', - name: 'Kozel', + brand: "Pilsner Urqell", + name: "Kozel", degree: 11, - packaging: 'can' + packaging: "can", }; // Remove export const del = yup.object({ - _id: yup.string().required() + _id: yup.string().required(), }); export interface IDel extends yup.InferType {} export const delExam: IDel = { - _id: '6352b303b71cb62222f39895' + _id: "6352b303b71cb62222f39895", }; // Update @@ -41,12 +41,17 @@ export const edit = yup.object({ degree: yup.number(), packaging: yup.string(), - //imgs: yup.mixed().when('$imgs', (imgs, schema) => - // Array.isArray(imgs) ? schema.array() : schema.string() - //) + //imgs: yup.mixed().when('$imgs', (imgs, schema) => + // Array.isArray(imgs) ? schema.array() : schema.string() + //) - imgs: yup.mixed().test('is-array-or-string', 'imgs must be either an array or a string', value => - Array.isArray(value) || typeof value === 'string') + imgs: yup + .mixed() + .test( + "is-array-or-string", + "imgs must be either an array or a string", + (value) => Array.isArray(value) || typeof value === "string", + ), //imgs: yup.mixed().when('isArray', { // is: Array.isArray, @@ -56,10 +61,10 @@ export const edit = yup.object({ }); export interface IEdit extends yup.InferType {} export const editExam: IEdit = { - _id: '6355b95dc03fad77bc380146', - brand: 'Pilsner Urqell', - name: 'Radegast', + _id: "6355b95dc03fad77bc380146", + brand: "Pilsner Urqell", + name: "Radegast", degree: 12, - packaging: 'bottle', - imgs: [] + packaging: "bottle", + imgs: [], }; diff --git a/api/src/validators/reviewValidator.ts b/api/src/validators/reviewValidator.ts index a458378..ae1799d 100644 --- a/api/src/validators/reviewValidator.ts +++ b/api/src/validators/reviewValidator.ts @@ -1,5 +1,5 @@ -import * as yup from 'yup' -import mongoose, { Schema } from 'mongoose' +import * as yup from "yup"; +import mongoose, { Schema } from "mongoose"; interface mongooseAddition { _id?: Schema.Types.ObjectId; @@ -7,39 +7,36 @@ interface mongooseAddition { updatedAt?: Schema.Types.Date; } -let objectIdSchema = yup.string().test( - 'is-objectId', - 'Invalid ObjectId', - (value: any) => mongoose.Types.ObjectId.isValid(value) -) +let objectIdSchema = yup + .string() + .test("is-objectId", "Invalid ObjectId", (value: any) => mongoose.Types.ObjectId.isValid(value)); // Add export const add = yup.object({ - beer_id: objectIdSchema, - foam: yup.number().min(1).max(3).required(), - bitter_sweetness: yup.number().min(1).max(5).required(), - taste: yup.number().min(1).max(5).required(), - packaging: yup.number().min(1).max(5).required(), - sourness: yup.boolean().required(), - would_again: yup.boolean().required() -}) + beer_id: objectIdSchema, + foam: yup.number().min(1).max(3).required(), + bitter_sweetness: yup.number().min(1).max(5).required(), + taste: yup.number().min(1).max(5).required(), + packaging: yup.number().min(1).max(5).required(), + sourness: yup.boolean().required(), + would_again: yup.boolean().required(), +}); export interface IReview extends yup.InferType, mongooseAddition {} export const addExam: IReview = { - beer_id: '6352b303b71cb62222f39895', - foam: 3, - bitter_sweetness: 2, - taste: 5, - packaging: 3, - sourness: false, - would_again: true -} + beer_id: "6352b303b71cb62222f39895", + foam: 3, + bitter_sweetness: 2, + taste: 5, + packaging: 3, + sourness: false, + would_again: true, +}; // Remove export const del = yup.object({ - _id: objectIdSchema.required() -}) + _id: objectIdSchema.required(), +}); export interface IDel extends yup.InferType {} export const delExam: IDel = { - _id: '6352b303b71cb62222f39895' + _id: "6352b303b71cb62222f39895", }; - diff --git a/api/tests/_setupFile.ts b/api/tests/_setupFile.ts index efe36b2..a5e20b8 100644 --- a/api/tests/_setupFile.ts +++ b/api/tests/_setupFile.ts @@ -1,4 +1,4 @@ -import { connectDB, dropDB, dropCollections } from '../src/utils/test_mongodb'; +import { connectDB, dropDB, dropCollections } from "../src/utils/test_mongodb"; beforeAll(async () => { await connectDB(); diff --git a/api/tests/auth.test.ts b/api/tests/auth.test.ts index 66c576c..667eb7b 100644 --- a/api/tests/auth.test.ts +++ b/api/tests/auth.test.ts @@ -1,22 +1,22 @@ -import supertest from 'supertest'; -import { app } from '../src/app'; -import { connectDB, dropDB, dropCollections } from '../src/utils/test_mongodb'; +import supertest from "supertest"; +import { app } from "../src/app"; +import { connectDB, dropDB, dropCollections } from "../src/utils/test_mongodb"; const request = supertest(app); export const getJWT = async () => { try { - const resReg: any = await request.post('/api/v1/auth/signup').send({ - email: 'test@example.local', - password: 'admin1234', - username: 'Test Test' + const resReg: any = await request.post("/api/v1/auth/signup").send({ + email: "test@example.local", + password: "admin1234", + username: "Test Test", }); - const resLog: any = await request.post('/api/auth/login').send({ - email: 'test@example.local', - password: 'admin1234' + const resLog: any = await request.post("/api/auth/login").send({ + email: "test@example.local", + password: "admin1234", }); - if (resLog.statusCode != 200) throw 'error while logging in'; + if (resLog.statusCode != 200) throw "error while logging in"; const body = JSON.parse(resLog.text); return Promise.resolve(body.data.jwt); @@ -31,194 +31,194 @@ export const getJWT = async () => { * @returns JWT cookie */ export async function login(): Promise { - const res = await request.post('/api/v1/auth/signin').send({ - email: 'thisistest@host.local', - password: 'Admin1234' + const res = await request.post("/api/v1/auth/signin").send({ + email: "thisistest@host.local", + password: "Admin1234", }); - return res.headers['set-cookie']; + return res.headers["set-cookie"]; } export async function signup(): Promise { - const res = await request.post('/api/v1/auth/signup').send({ - email: 'thisistest@host.local', - password: 'Admin1234', - username: 'Test Test' + const res = await request.post("/api/v1/auth/signup").send({ + email: "thisistest@host.local", + password: "Admin1234", + username: "Test Test", }); if (res.statusCode == 201) return true; return false; } -describe('POST /api/v1/auth/signup', () => { - describe('should drop validation error', () => { - it('should drop 400 (empty request))', async () => { - const res: any = await request.post('/api/v1/auth/signup').send({}); +describe("POST /api/v1/auth/signup", () => { + describe("should drop validation error", () => { + it("should drop 400 (empty request))", async () => { + const res: any = await request.post("/api/v1/auth/signup").send({}); expect(res.statusCode).toBe(400); }); - it('should drop 400 (email))', async () => { - const res: any = await request.post('/api/v1/auth/signup').send({ - email: '', - username: 'User Admin', - password: 'Admin1234' + it("should drop 400 (email))", async () => { + const res: any = await request.post("/api/v1/auth/signup").send({ + email: "", + username: "User Admin", + password: "Admin1234", }); - console.log(res) + console.log(res); const body = JSON.parse(res.text); expect(res.statusCode).toBe(400); - expect(body.data.path).toBe('email'); + expect(body.data.path).toBe("email"); }); - it('should drop 400 (username))', async () => { - const res: any = await request.post('/api/v1/auth/signup').send({ - email: 'admin@localhost.local', - username: '', - password: 'Admin1234' + it("should drop 400 (username))", async () => { + const res: any = await request.post("/api/v1/auth/signup").send({ + email: "admin@localhost.local", + username: "", + password: "Admin1234", }); const body = JSON.parse(res.text); expect(res.statusCode).toBe(400); - expect(body.data.path).toBe('username'); + expect(body.data.path).toBe("username"); }); - it('should drop 400 (password))', async () => { - const res: any = await request.post('/api/v1/auth/signup').send({ - email: 'admin@localhost.local', - username: 'User Admin', - password: '' + it("should drop 400 (password))", async () => { + const res: any = await request.post("/api/v1/auth/signup").send({ + email: "admin@localhost.local", + username: "User Admin", + password: "", }); const body = JSON.parse(res.text); expect(res.statusCode).toBe(400); - expect(body.data.path).toBe('password'); + expect(body.data.path).toBe("password"); }); - it('should drop 400 (password - min 8 chars', async () => { - const res = await request.post('/api/v1/auth/signup').send({ - email: 'admin@localhost.local', - username: 'User Admin', - password: 'Admin12' + it("should drop 400 (password - min 8 chars", async () => { + const res = await request.post("/api/v1/auth/signup").send({ + email: "admin@localhost.local", + username: "User Admin", + password: "Admin12", }); const body = JSON.parse(res.text); expect(res.statusCode).toBe(400); - expect(body.data.path).toBe('password'); + expect(body.data.path).toBe("password"); }); - it('should drop 400 (password - min 1 number', async () => { - const res = await request.post('/api/v1/auth/signup').send({ - email: 'admin@localhost.local', - username: 'User Admin', - password: 'Adminadmin' + it("should drop 400 (password - min 1 number", async () => { + const res = await request.post("/api/v1/auth/signup").send({ + email: "admin@localhost.local", + username: "User Admin", + password: "Adminadmin", }); const body = JSON.parse(res.text); expect(res.statusCode).toBe(400); - expect(body.data.path).toBe('password'); + expect(body.data.path).toBe("password"); }); - it('should drop 400 (password - min 1 uppercase', async () => { - const res = await request.post('/api/v1/auth/signup').send({ - email: 'admin@localhost.local', - username: 'User Admin', - password: 'admin1234' + it("should drop 400 (password - min 1 uppercase", async () => { + const res = await request.post("/api/v1/auth/signup").send({ + email: "admin@localhost.local", + username: "User Admin", + password: "admin1234", }); const body = JSON.parse(res.text); expect(res.statusCode).toBe(400); - expect(body.data.path).toBe('password'); + expect(body.data.path).toBe("password"); }); }); - test('should register an user', async () => { - const res: any = await request.post('/api/v1/auth/signup').send({ - email: 'thisistest@host.local', - password: 'Admin1234', - username: 'Test Test' + test("should register an user", async () => { + const res: any = await request.post("/api/v1/auth/signup").send({ + email: "thisistest@host.local", + password: "Admin1234", + username: "Test Test", }); expect(res.statusCode).toBe(201); }); }); -describe('POST /api/v1/auth/signin', () => { - const url = '/api/v1/auth/signin'; +describe("POST /api/v1/auth/signin", () => { + const url = "/api/v1/auth/signin"; - describe('should drop an validation error', () => { - it('should drop 400 (empty)', async () => { + describe("should drop an validation error", () => { + it("should drop 400 (empty)", async () => { const res = await request.post(url).send(); expect(res.statusCode).toBe(400); }); - it('should drop 400 (email)', async () => { + it("should drop 400 (email)", async () => { const res = await request.post(url).send({ - password: 'Admin1234' + password: "Admin1234", }); const body = JSON.parse(res.text); expect(res.statusCode).toBe(400); - expect(body.data.path).toBe('email'); + expect(body.data.path).toBe("email"); }); - it('should drop 400 (password)', async () => { + it("should drop 400 (password)", async () => { const res = await request.post(url).send({ - email: 'thisistest@host.local' + email: "thisistest@host.local", }); const body = JSON.parse(res.text); expect(res.statusCode).toBe(400); - expect(body.data.path).toBe('password'); + expect(body.data.path).toBe("password"); }); }); - test('should drop 401', async () => { + test("should drop 401", async () => { const res = await request.post(url).send({ - email: 'thisistest@host.local', - password: 'Test12365465132' + email: "thisistest@host.local", + password: "Test12365465132", }); expect(res.statusCode).toBe(401); - expect(res.header['set-cookie'][0]).toContain("jwt=; Max-Age=0") - expect(res.header['set-cookie'][1]).toContain("auth=false") + expect(res.header["set-cookie"][0]).toContain("jwt=; Max-Age=0"); + expect(res.header["set-cookie"][1]).toContain("auth=false"); }); - test('should login an user', async () => { + test("should login an user", async () => { const res: any = await request.post(url).send({ - email: 'thisistest@host.local', - password: 'Admin1234' + email: "thisistest@host.local", + password: "Admin1234", }); expect(res.statusCode).toBe(200); - expect(res.header['set-cookie'][0]).toContain("jwt=") - expect(res.header['set-cookie'][1]).toContain("auth=true") + expect(res.header["set-cookie"][0]).toContain("jwt="); + expect(res.header["set-cookie"][1]).toContain("auth=true"); }); }); -describe('POST /api/v1/auth/logout', () => { - const url = '/api/v1/auth/logout'; - test('should drop 401 error', async () => { +describe("POST /api/v1/auth/logout", () => { + const url = "/api/v1/auth/logout"; + test("should drop 401 error", async () => { const res = await request.post(url).send({}); expect(res.statusCode).toBe(401); }); - test('should logout an user', async () => { + test("should logout an user", async () => { const jwt = await login(); - const res = await request.post(url).set('Cookie', jwt).send(); + const res = await request.post(url).set("Cookie", jwt).send(); expect(res.statusCode).toBe(200); - expect(res.header['set-cookie'][0]).toContain("jwt=; Max-Age=0") - expect(res.header['set-cookie'][1]).toContain("auth=false") + expect(res.header["set-cookie"][0]).toContain("jwt=; Max-Age=0"); + expect(res.header["set-cookie"][1]).toContain("auth=false"); }); }); -describe('GET /api/v1/auth/status', () => { - const url = '/api/v1/auth/status'; - test('should return login status 401', async () => { +describe("GET /api/v1/auth/status", () => { + const url = "/api/v1/auth/status"; + test("should return login status 401", async () => { const res = await request.get(url).send(); expect(res.statusCode).toBe(401); }); - test('should return login status 200', async () => { + test("should return login status 200", async () => { const jwt = await login(); - const res = await request.get(url).set('Cookie', jwt).send(); + const res = await request.get(url).set("Cookie", jwt).send(); expect(res.statusCode).toBe(200); - expect(res.body.data.username).toBe("Test Test") - expect(res.body.data.email).toBe("thisistest@host.local") - expect(res.body.data.password).toBeUndefined() + expect(res.body.data.username).toBe("Test Test"); + expect(res.body.data.email).toBe("thisistest@host.local"); + expect(res.body.data.password).toBeUndefined(); }); -}); \ No newline at end of file +}); diff --git a/api/tests/beer.test.ts b/api/tests/beer.test.ts index fcb9447..a5e9c41 100644 --- a/api/tests/beer.test.ts +++ b/api/tests/beer.test.ts @@ -1,166 +1,166 @@ -import supertest from 'supertest'; -import { app } from '../src/app'; -import { login } from './auth.test'; -import { addExam, delExam, editExam } from '../src/validators/beerValidator'; +import supertest from "supertest"; +import { app } from "../src/app"; +import { login } from "./auth.test"; +import { addExam, delExam, editExam } from "../src/validators/beerValidator"; const request = supertest(app); -describe('POST /api/v1/beer/add', () => { - const url = '/api/v1/beer/add'; - test('should drop 401 error', async () => { +describe("POST /api/v1/beer/add", () => { + const url = "/api/v1/beer/add"; + test("should drop 401 error", async () => { const res = await request.post(url).send({}); expect(res.statusCode).toBe(401); }); - test('should drop 400 ()', async () => { + test("should drop 400 ()", async () => { const jwt = await login(); - const res = await request.post(url).set('Cookie', jwt).send({}); + const res = await request.post(url).set("Cookie", jwt).send({}); expect(res.statusCode).toBe(400); }); - test('should drop 400 (brand)', async () => { + test("should drop 400 (brand)", async () => { const jwt = await login(); const body: any = { ...addExam }; delete body.brand; - const res = await request.post(url).set('Cookie', jwt).send(body); + const res = await request.post(url).set("Cookie", jwt).send(body); expect(res.statusCode).toBe(400); }); - test('should drop 201', async () => { + test("should drop 201", async () => { const jwt = await login(); - const res = await request.post(url).set('Cookie', jwt).send(addExam); + const res = await request.post(url).set("Cookie", jwt).send(addExam); expect(res.statusCode).toBe(201); }); }); -describe('GET /api/v1/beer/get', () => { - const url = '/api/v1/beer/get'; +describe("GET /api/v1/beer/get", () => { + const url = "/api/v1/beer/get"; - test('should drop 401', async () => { + test("should drop 401", async () => { const res = await request.get(url).send(); expect(res.statusCode).toBe(401); }); - test('should drop 200', async () => { + test("should drop 200", async () => { const jwt = await login(); - const res = await request.get(url).set('Cookie', jwt).send(); + const res = await request.get(url).set("Cookie", jwt).send(); expect(res.statusCode).toBe(200); }); }); -describe('POST /api/v1/beer/del', () => { - const url = '/api/v1/beer/del'; +describe("POST /api/v1/beer/del", () => { + const url = "/api/v1/beer/del"; - test('should drop 401', async () => { + test("should drop 401", async () => { const res = await request.post(url).send(); expect(res.statusCode).toBe(401); }); - test('should drop 400', async () => { + test("should drop 400", async () => { const jwt = await login(); - const res = await request.post(url).set('Cookie', jwt).send(delExam); + const res = await request.post(url).set("Cookie", jwt).send(delExam); expect(res.statusCode).toBe(400); }); - test('should drop 400', async () => { + test("should drop 400", async () => { const jwt = await login(); - const res = await request.post(url).set('Cookie', jwt).send({ - _id: 'thisWillNotWork' + const res = await request.post(url).set("Cookie", jwt).send({ + _id: "thisWillNotWork", }); expect(res.statusCode).toBe(400); }); - test('should drop 200', async () => { + test("should drop 200", async () => { const jwt = await login(); - const req = await request.post('/api/v1/beer/add').set('Cookie', jwt).send(addExam); + const req = await request.post("/api/v1/beer/add").set("Cookie", jwt).send(addExam); const id = req.body.data._id; - const res = await request.post(url).set('Cookie', jwt).send({ - _id: id + const res = await request.post(url).set("Cookie", jwt).send({ + _id: id, }); expect(res.statusCode).toBe(200); }); }); -describe('POST /api/v1/beer/edit', () => { - const url = '/api/v1/beer/edit'; +describe("POST /api/v1/beer/edit", () => { + const url = "/api/v1/beer/edit"; - test('should drop 401', async () => { + test("should drop 401", async () => { const res = await request.post(url).send(); expect(res.statusCode).toBe(401); }); - test('should drop 400', async () => { + test("should drop 400", async () => { const jwt = await login(); const payload: any = { ...editExam }; delete payload._id; - const res = await request.post(url).set('Cookie', jwt).send(payload); + const res = await request.post(url).set("Cookie", jwt).send(payload); expect(res.statusCode).toBe(400); }); - test('should drop 200', async () => { + test("should drop 200", async () => { const jwt = await login(); const payload: any = { ...editExam }; delete payload.name; - const res = await request.post(url).set('Cookie', jwt).send(payload); + const res = await request.post(url).set("Cookie", jwt).send(payload); expect(res.statusCode).toBe(200); }); - test('should drop 200', async () => { + test("should drop 200", async () => { const jwt = await login(); const payload: any = { ...editExam }; delete payload.degree; - const res = await request.post(url).set('Cookie', jwt).send(payload); + const res = await request.post(url).set("Cookie", jwt).send(payload); expect(res.statusCode).toBe(200); }); - test('should drop 200', async () => { + test("should drop 200", async () => { const jwt = await login(); const payload: any = { ...editExam }; delete payload.packaging; - const res = await request.post(url).set('Cookie', jwt).send(payload); + const res = await request.post(url).set("Cookie", jwt).send(payload); expect(res.statusCode).toBe(200); }); - test('should drop 200', async () => { + test("should drop 200", async () => { const jwt = await login(); const payload: any = { ...editExam }; delete payload.brand; - const res = await request.post(url).set('Cookie', jwt).send(payload); + const res = await request.post(url).set("Cookie", jwt).send(payload); expect(res.statusCode).toBe(200); }); - test('should drop 200', async () => { + test("should drop 200", async () => { const jwt = await login(); - const req = await request.post('/api/v1/beer/add').set('Cookie', jwt).send(addExam); + const req = await request.post("/api/v1/beer/add").set("Cookie", jwt).send(addExam); const _id = req.body.data._id; const payload = { ...editExam, _id: _id }; - let res = await request.post(url).set('Cookie', jwt).send(payload); + let res = await request.post(url).set("Cookie", jwt).send(payload); delete res.body.data._id; delete res.body.data.__v; @@ -172,4 +172,4 @@ describe('POST /api/v1/beer/edit', () => { expect(res.statusCode).toBe(200); expect(eq).toBe(true); }); -}); \ No newline at end of file +}); diff --git a/api/tests/docs.test.ts b/api/tests/docs.test.ts index 22d2157..c9bd0ed 100644 --- a/api/tests/docs.test.ts +++ b/api/tests/docs.test.ts @@ -1,12 +1,12 @@ -import request from 'supertest'; -import { app } from '../src/app'; +import request from "supertest"; +import { app } from "../src/app"; -describe('GET /api/v1', () => { - describe('should return json with docs', () => { - test('should respond with a 200 status code', async () => { - const response = await request(app).get('/api/v1').send({}); - expect(response.headers['content-type']).toMatch(/json/); +describe("GET /api/v1", () => { + describe("should return json with docs", () => { + test("should respond with a 200 status code", async () => { + const response = await request(app).get("/api/v1").send({}); + expect(response.headers["content-type"]).toMatch(/json/); expect(response.statusCode).toBe(200); }); }); -}); \ No newline at end of file +}); diff --git a/api/tests/review.test.ts b/api/tests/review.test.ts index 88b3dee..011df1b 100644 --- a/api/tests/review.test.ts +++ b/api/tests/review.test.ts @@ -1,32 +1,32 @@ -import supertest from 'supertest'; -import { app } from '../src/app'; -import { login } from './auth.test'; +import supertest from "supertest"; +import { app } from "../src/app"; +import { login } from "./auth.test"; //import { addExam, delExam, editExam } from '../src/validators/beerValidator'; const request = supertest(app); -describe('POST /api/v1/review/add', () => { - const url = '/api/v1/review/add'; - test('should drop 401 error', async () => { +describe("POST /api/v1/review/add", () => { + const url = "/api/v1/review/add"; + test("should drop 401 error", async () => { const res = await request.post(url).send({}); expect(res.statusCode).toBe(401); }); - test('should drop 400 ()', async () => { + test("should drop 400 ()", async () => { const jwt = await login(); - const res = await request.post(url).set('Cookie', jwt).send({}); + const res = await request.post(url).set("Cookie", jwt).send({}); - console.log("TEST", await res.body) + console.log("TEST", await res.body); expect(res.statusCode).toBe(400); }); -// test('should drop 201', async () => { -// const jwt = await login(); -// const res = await request.post(url).set('Cookie', jwt).send(addExam); -// -// expect(res.statusCode).toBe(201); -// }); + // test('should drop 201', async () => { + // const jwt = await login(); + // const res = await request.post(url).set('Cookie', jwt).send(addExam); + // + // expect(res.statusCode).toBe(201); + // }); }); //describe('GET /api/v1/beer/get', () => { @@ -45,5 +45,3 @@ describe('POST /api/v1/review/add', () => { // expect(res.statusCode).toBe(200); // }); //}); - - -- 2.45.2 From 1c97262ee3431562e9532256e0e71d43decc4aaf Mon Sep 17 00:00:00 2001 From: Filip Rojek Date: Sun, 12 May 2024 22:15:54 +0200 Subject: [PATCH 4/4] Added: tests for reviews, Reviews GET API endpoint; Fixed: tests for beers --- api/src/routes/api_v1.ts | 4 +- api/tests/beer.test.ts | 27 +++++++++++ api/tests/review.test.ts | 100 +++++++++++++++++++++++++++++---------- 3 files changed, 106 insertions(+), 25 deletions(-) diff --git a/api/src/routes/api_v1.ts b/api/src/routes/api_v1.ts index f05be66..d1d2233 100644 --- a/api/src/routes/api_v1.ts +++ b/api/src/routes/api_v1.ts @@ -10,6 +10,7 @@ import validate from "../middlewares/validateRequest"; import valMulter from "../middlewares/validateMulterRequest"; import * as AuthVal from "../validators/authValidator"; import * as BVal from "../validators/beerValidator"; +import * as RVal from "../validators/reviewValidator"; const upload = multer({ dest: path.resolve(__dirname, "../../uploads") }); @@ -35,6 +36,7 @@ router.post( beerController.edit_post, ); -router.post("/review/add", requireAuth, reviewController.add_post); +router.post("/review/add", [requireAuth, validate(RVal.add)], reviewController.add_post); +router.get("/review/get", requireAuth, reviewController.get_get); export default router; diff --git a/api/tests/beer.test.ts b/api/tests/beer.test.ts index a5e9c41..cd76f0a 100644 --- a/api/tests/beer.test.ts +++ b/api/tests/beer.test.ts @@ -19,6 +19,33 @@ describe("POST /api/v1/beer/add", () => { expect(res.statusCode).toBe(400); }); + test("should drop 400 (name)", async () => { + const jwt = await login(); + const body: any = { ...addExam }; + delete body.name; + const res = await request.post(url).set("Cookie", jwt).send(body); + + expect(res.statusCode).toBe(400); + }); + + test("should drop 400 (degree)", async () => { + const jwt = await login(); + const body: any = { ...addExam }; + delete body.degree; + const res = await request.post(url).set("Cookie", jwt).send(body); + + expect(res.statusCode).toBe(400); + }); + + test("should drop 400 (packaging)", async () => { + const jwt = await login(); + const body: any = { ...addExam }; + delete body.packaging; + const res = await request.post(url).set("Cookie", jwt).send(body); + + expect(res.statusCode).toBe(400); + }); + test("should drop 400 (brand)", async () => { const jwt = await login(); const body: any = { ...addExam }; diff --git a/api/tests/review.test.ts b/api/tests/review.test.ts index 011df1b..68801f2 100644 --- a/api/tests/review.test.ts +++ b/api/tests/review.test.ts @@ -1,7 +1,7 @@ import supertest from "supertest"; import { app } from "../src/app"; import { login } from "./auth.test"; -//import { addExam, delExam, editExam } from '../src/validators/beerValidator'; +import { addExam, delExam } from "../src/validators/reviewValidator"; const request = supertest(app); @@ -16,32 +16,84 @@ describe("POST /api/v1/review/add", () => { const jwt = await login(); const res = await request.post(url).set("Cookie", jwt).send({}); - console.log("TEST", await res.body); + expect(res.statusCode).toBe(400); + }); + + test("should drop 400 (foam)", async () => { + const jwt = await login(); + const body: any = { ...addExam }; + delete body.foam; + const res = await request.post(url).set("Cookie", jwt).send(body); expect(res.statusCode).toBe(400); }); - // test('should drop 201', async () => { - // const jwt = await login(); - // const res = await request.post(url).set('Cookie', jwt).send(addExam); - // - // expect(res.statusCode).toBe(201); - // }); + test("should drop 400 (bitter_sweetness)", async () => { + const jwt = await login(); + const body: any = { ...addExam }; + delete body.bitter_sweetness; + const res = await request.post(url).set("Cookie", jwt).send(body); + + expect(res.statusCode).toBe(400); + }); + + test("should drop 400 (taste)", async () => { + const jwt = await login(); + const body: any = { ...addExam }; + delete body.taste; + const res = await request.post(url).set("Cookie", jwt).send(body); + + expect(res.statusCode).toBe(400); + }); + + test("should drop 400 (packaging)", async () => { + const jwt = await login(); + const body: any = { ...addExam }; + delete body.packaging; + const res = await request.post(url).set("Cookie", jwt).send(body); + + expect(res.statusCode).toBe(400); + }); + + test("should drop 400 (sourness)", async () => { + const jwt = await login(); + const body: any = { ...addExam }; + delete body.sourness; + const res = await request.post(url).set("Cookie", jwt).send(body); + + expect(res.statusCode).toBe(400); + }); + + test("should drop 400 (would_again)", async () => { + const jwt = await login(); + const body: any = { ...addExam }; + delete body.would_again; + const res = await request.post(url).set("Cookie", jwt).send(body); + + expect(res.statusCode).toBe(400); + }); + + test("should drop 201", async () => { + const jwt = await login(); + const res = await request.post(url).set("Cookie", jwt).send(addExam); + + expect(res.statusCode).toBe(201); + }); }); -//describe('GET /api/v1/beer/get', () => { -// const url = '/api/v1/beer/get'; -// -// test('should drop 401', async () => { -// const res = await request.get(url).send(); -// -// expect(res.statusCode).toBe(401); -// }); -// -// test('should drop 200', async () => { -// const jwt = await login(); -// const res = await request.get(url).set('Cookie', jwt).send(); -// -// expect(res.statusCode).toBe(200); -// }); -//}); +describe("GET /api/v1/review/get", () => { + const url = "/api/v1/review/get"; + + test("should drop 401", async () => { + const res = await request.get(url).send(); + + expect(res.statusCode).toBe(401); + }); + + test("should drop 200", async () => { + const jwt = await login(); + const res = await request.get(url).set("Cookie", jwt).send(); + + expect(res.statusCode).toBe(200); + }); +}); -- 2.45.2