From 60e1b0dd9bb068fdbc67bb2715f36bfbaf8b0fbf Mon Sep 17 00:00:00 2001 From: Li Wenyun Date: Sat, 21 Sep 2024 14:42:47 +0800 Subject: [PATCH] new today --- package-lock.json | 30 +- package.json | 1 + src/controller/tag-controller.ts | 12 + src/controller/user-controller.ts | 46 ++ .../20240921052647_init/migration.sql | 69 +++ src/prisma/migrations/migration_lock.toml | 3 + src/prisma/schema.prisma | 49 +- src/routes/articles-routes.ts | 510 +++++++++--------- src/routes/tag-routes.ts | 18 +- src/routes/users-routes.ts | 178 +++--- 10 files changed, 560 insertions(+), 356 deletions(-) create mode 100644 src/controller/tag-controller.ts create mode 100644 src/controller/user-controller.ts create mode 100644 src/prisma/migrations/20240921052647_init/migration.sql create mode 100644 src/prisma/migrations/migration_lock.toml diff --git a/package-lock.json b/package-lock.json index 7175e6d..c1c3bd1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,7 @@ "version": "0.0.0", "license": "ISC", "dependencies": { + "@prisma/client": "^5.19.1", "body-parser": "^1.19.0", "compression": "1.7.4", "cors": "2.8.5", @@ -129,17 +130,34 @@ "kuler": "^2.0.0" } }, + "node_modules/@prisma/client": { + "version": "5.19.1", + "resolved": "https://registry.npmmirror.com/@prisma/client/-/client-5.19.1.tgz", + "integrity": "sha512-x30GFguInsgt+4z5I4WbkZP2CGpotJMUXy+Gl/aaUjHn2o1DnLYNTA+q9XdYmAQZM8fIIkvUiA2NpgosM3fneg==", + "hasInstallScript": true, + "engines": { + "node": ">=16.13" + }, + "peerDependencies": { + "prisma": "*" + }, + "peerDependenciesMeta": { + "prisma": { + "optional": true + } + } + }, "node_modules/@prisma/debug": { "version": "5.19.1", "resolved": "https://registry.npmmirror.com/@prisma/debug/-/debug-5.19.1.tgz", "integrity": "sha512-lAG6A6QnG2AskAukIEucYJZxxcSqKsMK74ZFVfCTOM/7UiyJQi48v6TQ47d6qKG3LbMslqOvnTX25dj/qvclGg==", - "dev": true + "devOptional": true }, "node_modules/@prisma/engines": { "version": "5.19.1", "resolved": "https://registry.npmmirror.com/@prisma/engines/-/engines-5.19.1.tgz", "integrity": "sha512-kR/PoxZDrfUmbbXqqb8SlBBgCjvGaJYMCOe189PEYzq9rKqitQ2fvT/VJ8PDSe8tTNxhc2KzsCfCAL+Iwm/7Cg==", - "dev": true, + "devOptional": true, "hasInstallScript": true, "dependencies": { "@prisma/debug": "5.19.1", @@ -152,13 +170,13 @@ "version": "5.19.1-2.69d742ee20b815d88e17e54db4a2a7a3b30324e3", "resolved": "https://registry.npmmirror.com/@prisma/engines-version/-/engines-version-5.19.1-2.69d742ee20b815d88e17e54db4a2a7a3b30324e3.tgz", "integrity": "sha512-xR6rt+z5LnNqTP5BBc+8+ySgf4WNMimOKXRn6xfNRDSpHvbOEmd7+qAOmzCrddEc4Cp8nFC0txU14dstjH7FXA==", - "dev": true + "devOptional": true }, "node_modules/@prisma/fetch-engine": { "version": "5.19.1", "resolved": "https://registry.npmmirror.com/@prisma/fetch-engine/-/fetch-engine-5.19.1.tgz", "integrity": "sha512-pCq74rtlOVJfn4pLmdJj+eI4P7w2dugOnnTXpRilP/6n5b2aZiA4ulJlE0ddCbTPkfHmOL9BfaRgA8o+1rfdHw==", - "dev": true, + "devOptional": true, "dependencies": { "@prisma/debug": "5.19.1", "@prisma/engines-version": "5.19.1-2.69d742ee20b815d88e17e54db4a2a7a3b30324e3", @@ -169,7 +187,7 @@ "version": "5.19.1", "resolved": "https://registry.npmmirror.com/@prisma/get-platform/-/get-platform-5.19.1.tgz", "integrity": "sha512-sCeoJ+7yt0UjnR+AXZL7vXlg5eNxaFOwC23h0KvW1YIXUoa7+W2ZcAUhoEQBmJTW4GrFqCuZ8YSP0mkDa4k3Zg==", - "dev": true, + "devOptional": true, "dependencies": { "@prisma/debug": "5.19.1" } @@ -3867,7 +3885,7 @@ "version": "5.19.1", "resolved": "https://registry.npmmirror.com/prisma/-/prisma-5.19.1.tgz", "integrity": "sha512-c5K9MiDaa+VAAyh1OiYk76PXOme9s3E992D7kvvIOhCrNsBQfy2mP2QAQtX0WNj140IgG++12kwZpYB9iIydNQ==", - "dev": true, + "devOptional": true, "hasInstallScript": true, "dependencies": { "@prisma/engines": "5.19.1" diff --git a/package.json b/package.json index a4dac17..a870ce5 100644 --- a/package.json +++ b/package.json @@ -48,6 +48,7 @@ "typescript": "^3.9.6" }, "dependencies": { + "@prisma/client": "^5.19.1", "body-parser": "^1.19.0", "compression": "1.7.4", "cors": "2.8.5", diff --git a/src/controller/tag-controller.ts b/src/controller/tag-controller.ts new file mode 100644 index 0000000..5a1e01a --- /dev/null +++ b/src/controller/tag-controller.ts @@ -0,0 +1,12 @@ +import { PrismaClient } from '@prisma/client' +import { Request, Response } from 'express'; + +const prisma = new PrismaClient() +export const getTags = async (req: Request, res: Response) => { + try { + const response = await prisma.article.findMany() + res.status(200).json(response) + } catch (error) { + res.status(500).json({ msg: error.message }) + } +} \ No newline at end of file diff --git a/src/controller/user-controller.ts b/src/controller/user-controller.ts new file mode 100644 index 0000000..5d1d497 --- /dev/null +++ b/src/controller/user-controller.ts @@ -0,0 +1,46 @@ +import { PrismaClient } from '@prisma/client' +import { Request, Response } from 'express'; +import passport from 'passport'; +import { authentication } from "../utilities/authentication"; + +const prisma = new PrismaClient() + +export const getUsers = async (req: Request, res: Response) => { + try { + const response = await prisma.user.findUnique({ + where: { + id: Number(req.params.id), + }, + }) + res.status(200).json(response) + } catch (error) { + res.status(500).json({ msg: error.message }) + } +} + +export const registerUsers = async (req: Request, res: Response) => { + try { + const response = await prisma.article.findMany() + res.status(200).json(response) + } catch (error) { + res.status(500).json({ msg: error.message }) + } +} + +export const postUsers = async (req: Request, res: Response) => { + try { + const response = await prisma.article.findMany() + res.status(200).json(response) + } catch (error) { + res.status(500).json({ msg: error.message }) + } +} + +export const loginUsers = async (req: Request, res: Response) => { + try { + const response = await prisma.article.findMany() + res.status(200).json(response) + } catch (error) { + res.status(500).json({ msg: error.message }) + } +} \ No newline at end of file diff --git a/src/prisma/migrations/20240921052647_init/migration.sql b/src/prisma/migrations/20240921052647_init/migration.sql new file mode 100644 index 0000000..6d3f299 --- /dev/null +++ b/src/prisma/migrations/20240921052647_init/migration.sql @@ -0,0 +1,69 @@ +-- CreateTable +CREATE TABLE "Article" ( + "id" SERIAL NOT NULL, + "slug" TEXT NOT NULL, + "title" TEXT NOT NULL, + "description" TEXT NOT NULL, + "body" TEXT NOT NULL, + "tagList" TEXT[], + "favoritesCount" INTEGER NOT NULL DEFAULT 0, + "authorId" INTEGER NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "Article_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "Comment" ( + "id" SERIAL NOT NULL, + "body" TEXT NOT NULL, + "authorId" INTEGER NOT NULL, + "articleId" INTEGER NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "Comment_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "User" ( + "id" SERIAL NOT NULL, + + CONSTRAINT "User_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "Profile" ( + "id" SERIAL NOT NULL, + "email" TEXT NOT NULL, + "username" TEXT NOT NULL, + "bio" TEXT NOT NULL, + "image" TEXT NOT NULL, + "following" BOOLEAN NOT NULL, + "userId" INTEGER NOT NULL, + + CONSTRAINT "Profile_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "Article_slug_key" ON "Article"("slug"); + +-- CreateIndex +CREATE UNIQUE INDEX "Article_authorId_key" ON "Article"("authorId"); + +-- CreateIndex +CREATE UNIQUE INDEX "Profile_email_key" ON "Profile"("email"); + +-- CreateIndex +CREATE UNIQUE INDEX "Profile_userId_key" ON "Profile"("userId"); + +-- AddForeignKey +ALTER TABLE "Article" ADD CONSTRAINT "Article_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Comment" ADD CONSTRAINT "Comment_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Comment" ADD CONSTRAINT "Comment_articleId_fkey" FOREIGN KEY ("articleId") REFERENCES "Article"("id") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Profile" ADD CONSTRAINT "Profile_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/src/prisma/migrations/migration_lock.toml b/src/prisma/migrations/migration_lock.toml new file mode 100644 index 0000000..fbffa92 --- /dev/null +++ b/src/prisma/migrations/migration_lock.toml @@ -0,0 +1,3 @@ +# Please do not edit this file manually +# It should be added in your version-control system (i.e. Git) +provider = "postgresql" \ No newline at end of file diff --git a/src/prisma/schema.prisma b/src/prisma/schema.prisma index 1612243..f63a16b 100644 --- a/src/prisma/schema.prisma +++ b/src/prisma/schema.prisma @@ -9,6 +9,51 @@ generator client { } datasource db { - provider = "sqlite" - url = "file:dev.db" + provider = "postgresql" + url = env("DATABASE_URL") + shadowDatabaseUrl = env("SHADOW_DATABASE_URL") +} + +model Article { + id Int @id @default(autoincrement()) + slug String @unique + title String + description String + body String + tagList String[] + favoritesCount Int @default(0) + author User @relation(fields: [authorId], references: [id]) + authorId Int @unique + createdAt DateTime @default(now()) + Comment Comment[] +} + +model Comment { + id Int @id @default(autoincrement()) + body String + author User @relation(fields: [authorId], references: [id]) + authorId Int + article Article @relation(fields: [articleId], references: [id]) + articleId Int + createdAt DateTime @default(now()) +} + +model User { + id Int @id @default(autoincrement()) + Article Article? + Comment Comment[] + Profile Profile? + createdAt DateTime @default(now()) + updatedAt DateTime @default(now()) +} + +model Profile { + id Int @id @default(autoincrement()) + email String @unique + username String + bio String + image String + following Boolean + user User @relation(fields: [userId], references: [id]) + userId Int @unique } diff --git a/src/routes/articles-routes.ts b/src/routes/articles-routes.ts index c8189e3..83db3a2 100644 --- a/src/routes/articles-routes.ts +++ b/src/routes/articles-routes.ts @@ -1,302 +1,316 @@ import { Request, Response, Router } from 'express'; import { authentication } from '../utilities/authentication'; -import { User } from '../database/models/user.model'; -import { Article } from "../database/models/article.model"; -import { Comment } from "../database/models/comment.model"; +// import { User } from '../database/models/user.model'; +// import { Article } from "../database/models/article.model"; +// import { Comment } from "../database/models/comment.model"; +const { PrismaClient } = require('@prisma/client'); const router: Router = Router(); +const prisma = new PrismaClient(); // Preload article objects on routes with ':article' -router.param('article', function (req: Request, res: Response, next, slug) { - Article.findOne({slug: slug}) - .populate('author') - .then(function (article) { - if (!article) { - return res.sendStatus(404); - } +// router.param('article', function (req: Request, res: Response, next, slug) { +// const response = prisma.Article.findOne(slug) +// Article.findOne({slug: slug}) +// .populate('author') +// .then(function (article) { +// if (!article) { +// return res.sendStatus(404); +// } - req.article = article; +// req.article = article; - return next(); - }).catch(next); -}); +// return next(); +// }).catch(next); +// }); -router.param('comment', function (req: Request, res: Response, next, id) { - Comment.findById(id).then(function (comment) { - if (!comment) { - return res.sendStatus(404); - } +// router.param('comment', function (req: Request, res: Response, next, id) { +// const response = prisma.Comment.findById(id) + +// Comment.findById(id).then(function (comment) { +// if (!comment) { +// return res.sendStatus(404); +// } - req.comment = comment; +// req.comment = comment; - return next(); - }).catch(next); -}); +// return next(); +// }).catch(next); +// }); -router.get('/', authentication.optional, function (req: Request, res: Response, next) { - const query: any = {}; - let limit = 20; - let offset = 0; +// router.get('/', authentication.optional, function (req: Request, res: Response, next) { +// const query: any = {}; +// let limit = 20; +// let offset = 0; - if (typeof req.query.limit !== 'undefined') { - limit = parseInt(req.query.limit as string); - } +// if (typeof req.query.limit !== 'undefined') { +// limit = parseInt(req.query.limit as string); +// } - if (typeof req.query.offset !== 'undefined') { - offset = parseInt(req.query.offset as string); - } +// if (typeof req.query.offset !== 'undefined') { +// offset = parseInt(req.query.offset as string); +// } - if (typeof req.query.tag !== 'undefined') { - query.tagList = {"$in": [req.query.tag]}; - } +// if (typeof req.query.tag !== 'undefined') { +// query.tagList = {"$in": [req.query.tag]}; +// } - Promise.all([ - req.query.author ? User.findOne({username: req.query.author as string}) : null, - req.query.favorited ? User.findOne({username: req.query.favorited as string}) : null - ]).then(function (results) { - const author = results[0]; - const favoriter = results[1]; +// Promise.all([ +// req.query.author ? User.findOne({username: req.query.author as string}) : null, +// req.query.favorited ? User.findOne({username: req.query.favorited as string}) : null +// ]).then(function (results) { +// const author = results[0]; +// const favoriter = results[1]; - if (author) { - query.author = author._id; - } +// if (author) { +// query.author = author._id; +// } - if (favoriter) { - query._id = {$in: favoriter.favorites}; - } else if (req.query.favorited) { - query._id = {$in: []}; - } +// if (favoriter) { +// query._id = {$in: favoriter.favorites}; +// } else if (req.query.favorited) { +// query._id = {$in: []}; +// } - return Promise.all([ - Article.find(query) - .limit(Number(limit)) - .skip(Number(offset)) - .sort({createdAt: 'desc'}) - .populate('author') - .exec(), - Article.count(query).exec(), - req.payload ? User.findById(req.payload.id) : null, - ]).then(function (results) { - const articles = results[0]; - const articlesCount = results[1]; - const user = results[2]; +// return Promise.all([ +// Article.find(query) +// .limit(Number(limit)) +// .skip(Number(offset)) +// .sort({createdAt: 'desc'}) +// .populate('author') +// .exec(), +// Article.count(query).exec(), +// req.payload ? User.findById(req.payload.id) : null, +// ]).then(function (results) { +// const articles = results[0]; +// const articlesCount = results[1]; +// const user = results[2]; - return res.json({ - articles : articles.map(function (article) { - return article.toJSONFor(user); - }), - articlesCount: articlesCount - }); - }); - }).catch(next); -}); +// return res.json({ +// articles : articles.map(function (article) { +// return article.toJSONFor(user); +// }), +// articlesCount: articlesCount +// }); +// }); +// }).catch(next); +// }); -router.get('/feed', authentication.required, function (req: Request, res: Response, next) { - let limit = 20; - let offset = 0; +// router.get('/feed', authentication.required, function (req: Request, res: Response, next) { +// let limit = 20; +// let offset = 0; - if (typeof req.query.limit !== 'undefined') { - limit = parseInt(req.query.limit as string); - } +// if (typeof req.query.limit !== 'undefined') { +// limit = parseInt(req.query.limit as string); +// } - if (typeof req.query.offset !== 'undefined') { - offset = parseInt(req.query.offset as string); - } +// if (typeof req.query.offset !== 'undefined') { +// offset = parseInt(req.query.offset as string); +// } - User.findById(req.payload.id).then(function (user) { - if (!user) { - return res.sendStatus(401); - } +// User.findById(req.payload.id).then(function (user) { +// if (!user) { +// return res.sendStatus(401); +// } - Promise.all([ - Article.find({author: {$in: user.following}}) - .limit(Number(limit)) - .skip(Number(offset)) - .populate('author') - .exec(), - Article.count({author: {$in: user.following}}) - ]).then(function (results) { - const articles = results[0]; - const articlesCount = results[1]; +// Promise.all([ +// Article.find({author: {$in: user.following}}) +// .limit(Number(limit)) +// .skip(Number(offset)) +// .populate('author') +// .exec(), +// Article.count({author: {$in: user.following}}) +// ]).then(function (results) { +// const articles = results[0]; +// const articlesCount = results[1]; - return res.json({ - articles : articles.map(function (article) { - return article.toJSONFor(user); - }), - articlesCount: articlesCount - }); - }).catch(next); - }); -}); +// return res.json({ +// articles : articles.map(function (article) { +// return article.toJSONFor(user); +// }), +// articlesCount: articlesCount +// }); +// }).catch(next); +// }); +// }); -router.post('/', authentication.required, function (req: Request, res: Response, next) { - User.findById(req.payload.id).then(function (user) { - if (!user) { - return res.sendStatus(401); - } +// router.post('/', authentication.required, function (req: Request, res: Response, next) { +// User.findById(req.payload.id).then(function (user) { +// if (!user) { +// return res.sendStatus(401); +// } - const article = new Article(req.body.article); +// const article = new Article(req.body.article); - article.author = user; +// article.author = user; - return article.save().then(function () { - console.log(article.author); - return res.json({article: article.toJSONFor(user)}); - }); - }).catch(next); -}); +// return article.save().then(function () { +// console.log(article.author); +// return res.json({article: article.toJSONFor(user)}); +// }); +// }).catch(next); +// }); -// return a article -router.get('/:article', authentication.optional, function (req: Request, res: Response, next) { - Promise.all([ - req.payload ? User.findById(req.payload.id) : null, - req.article.populate('author').execPopulate() - ]).then(function (results) { - const user = results[0]; +// // return a article +// router.get('/:article', authentication.optional, function (req: Request, res: Response, next) { +// Promise.all([ +// req.payload ? User.findById(req.payload.id) : null, +// req.article.populate('author').execPopulate() +// ]).then(function (results) { +// const user = results[0]; - return res.json({article: req.article.toJSONFor(user)}); - }).catch(next); -}); +// return res.json({article: req.article.toJSONFor(user)}); +// }).catch(next); +// }); -// update article -router.put('/:article', authentication.required, function (req: Request, res: Response, next) { - User.findById(req.payload.id).then(function (user) { - if (req.article.author._id.toString() === req.payload.id.toString()) { - if (typeof req.body.article.title !== 'undefined') { - req.article.title = req.body.article.title; - } +// // update article +// router.put('/:article', authentication.required, function (req: Request, res: Response, next) { +// User.findById(req.payload.id).then(function (user) { +// if (req.article.author._id.toString() === req.payload.id.toString()) { +// if (typeof req.body.article.title !== 'undefined') { +// req.article.title = req.body.article.title; +// } - if (typeof req.body.article.description !== 'undefined') { - req.article.description = req.body.article.description; - } +// if (typeof req.body.article.description !== 'undefined') { +// req.article.description = req.body.article.description; +// } - if (typeof req.body.article.body !== 'undefined') { - req.article.body = req.body.article.body; - } +// if (typeof req.body.article.body !== 'undefined') { +// req.article.body = req.body.article.body; +// } - if (typeof req.body.article.tagList !== 'undefined') { - req.article.tagList = req.body.article.tagList - } +// if (typeof req.body.article.tagList !== 'undefined') { +// req.article.tagList = req.body.article.tagList +// } - req.article.save().then(function (article) { - return res.json({article: article.toJSONFor(user)}); - }).catch(next); - } else { - return res.sendStatus(403); - } - }); -}); +// req.article.save().then(function (article) { +// return res.json({article: article.toJSONFor(user)}); +// }).catch(next); +// } else { +// return res.sendStatus(403); +// } +// }); +// }); -// delete article -router.delete('/:article', authentication.required, function (req: Request, res: Response, next) { - User.findById(req.payload.id).then(function (user) { - if (!user) { - return res.sendStatus(401); - } +// // delete article +// router.delete('/:article', authentication.required, function (req: Request, res: Response, next) { +// User.findById(req.payload.id).then(function (user) { +// if (!user) { +// return res.sendStatus(401); +// } - if (req.article.author._id.toString() === req.payload.id.toString()) { - return req.article.remove().then(function () { - return res.sendStatus(204); - }); - } else { - return res.sendStatus(403); - } - }).catch(next); -}); +// if (req.article.author._id.toString() === req.payload.id.toString()) { +// return req.article.remove().then(function () { +// return res.sendStatus(204); +// }); +// } else { +// return res.sendStatus(403); +// } +// }).catch(next); +// }); -// Favorite an article -router.post('/:article/favorite', authentication.required, function (req: Request, res: Response, next) { - const articleId = req.article._id; +// // Favorite an article +// router.post('/:article/favorite', authentication.required, function (req: Request, res: Response, next) { +// const articleId = req.article._id; - User.findById(req.payload.id).then(function (user) { - if (!user) { - return res.sendStatus(401); - } +// User.findById(req.payload.id).then(function (user) { +// if (!user) { +// return res.sendStatus(401); +// } - return user.favorite(articleId).then(function () { - return req.article.updateFavoriteCount().then(function (article) { - return res.json({article: article.toJSONFor(user)}); - }); - }); - }).catch(next); -}); +// return user.favorite(articleId).then(function () { +// return req.article.updateFavoriteCount().then(function (article) { +// return res.json({article: article.toJSONFor(user)}); +// }); +// }); +// }).catch(next); +// }); -// Unfavorite an article -router.delete('/:article/favorite', authentication.required, function (req: Request, res: Response, next) { - const articleId = req.article._id; +// // Unfavorite an article +// router.delete('/:article/favorite', authentication.required, function (req: Request, res: Response, next) { +// const articleId = req.article._id; - User.findById(req.payload.id).then(function (user) { - if (!user) { - return res.sendStatus(401); - } +// User.findById(req.payload.id).then(function (user) { +// if (!user) { +// return res.sendStatus(401); +// } - return user.unfavorite(articleId).then(function () { - return req.article.updateFavoriteCount().then(function (article) { - return res.json({article: article.toJSONFor(user)}); - }); - }); - }).catch(next); -}); +// return user.unfavorite(articleId).then(function () { +// return req.article.updateFavoriteCount().then(function (article) { +// return res.json({article: article.toJSONFor(user)}); +// }); +// }); +// }).catch(next); +// }); -// return an article's comments -router.get('/:article/comments', authentication.optional, function (req: Request, res: Response, next) { - Promise.resolve(req.payload ? User.findById(req.payload.id) : null).then(function (user) { - return req.article.populate({ - path : 'comments', - populate: { - path: 'author' - }, - options : { - sort: { - createdAt: 'desc' - } - } - }).execPopulate().then(function (article) { - return res.json({ - comments: req.article.comments.map(function (comment) { - return comment.toJSONFor(user); - }) - }); - }); - }).catch(next); -}); +// // return an article's comments +// router.get('/:article/comments', authentication.optional, function (req: Request, res: Response, next) { +// Promise.resolve(req.payload ? User.findById(req.payload.id) : null).then(function (user) { +// return req.article.populate({ +// path : 'comments', +// populate: { +// path: 'author' +// }, +// options : { +// sort: { +// createdAt: 'desc' +// } +// } +// }).execPopulate().then(function (article) { +// return res.json({ +// comments: req.article.comments.map(function (comment) { +// return comment.toJSONFor(user); +// }) +// }); +// }); +// }).catch(next); +// }); -// create a new comment -router.post('/:article/comments', authentication.required, function (req: Request, res: Response, next) { - User.findById(req.payload.id) - // @ts-ignore - .then(function (user) { - if (!user) { - return res.sendStatus(401); - } +// // create a new comment +// router.post('/:article/comments', authentication.required, function (req: Request, res: Response, next) { +// User.findById(req.payload.id) +// // @ts-ignore +// .then(function (user) { +// if (!user) { +// return res.sendStatus(401); +// } - const comment = new Comment(req.body.comment); - comment.article = req.article; - comment.author = user; +// const comment = new Comment(req.body.comment); +// comment.article = req.article; +// comment.author = user; - return comment.save().then(function () { - req.article.comments.push(comment); +// return comment.save().then(function () { +// req.article.comments.push(comment); - return req.article.save().then(function (article) { - res.json({comment: comment.toJSONFor(user)}); - }); - }); - }).catch(next); -}); +// return req.article.save().then(function (article) { +// res.json({comment: comment.toJSONFor(user)}); +// }); +// }); +// }).catch(next); +// }); -router.delete('/:article/comments/:comment', authentication.required, function (req: Request, res: Response, next) { - if (req.comment.author.toString() === req.payload.id.toString()) { - // @ts-ignore - req.article.comments.remove(req.comment._id); - req.article.save() - .then(() => Comment.find({_id: req.comment._id}).remove().exec()) - .then(function () { - res.sendStatus(204); - }); - } else { - res.sendStatus(403); - } -}); +// router.delete('/:article/comments/:comment', authentication.required, function (req: Request, res: Response, next) { +// if (req.comment.author.toString() === req.payload.id.toString()) { +// // @ts-ignore +// req.article.comments.remove(req.comment._id); +// req.article.save() +// .then(() => Comment.find({_id: req.comment._id}).remove().exec()) +// .then(function () { +// res.sendStatus(204); +// }); +// } else { +// res.sendStatus(403); +// } +// }); + +router.get('/articles/:slug', getTags); +router.delete('/articles/:slug', getTags); +router.put('/articles/:slug', getTags); +router.post('/articles/:slug/favorite',favorite_an_article); +router.delete('/articles/:slug/favorite', unfavorite_an_article); +router.post('/:articles/comments',favorite_an_article); +router.delete('/:articles/comments/:comments', unfavorite_an_article); +router.get('articles/:slug/comments', getTags); export const ArticlesRoutes: Router = router; diff --git a/src/routes/tag-routes.ts b/src/routes/tag-routes.ts index 1fc547c..1edd568 100644 --- a/src/routes/tag-routes.ts +++ b/src/routes/tag-routes.ts @@ -1,22 +1,14 @@ -import { Article } from '../database/models/article.model'; -import { NextFunction, Request, Response, Router } from 'express'; +// import { Article } from '../database/models/article.model'; +import { Request, Response, Router } from 'express'; +import { getTags } from '../controller/tag-controller'; + const router: Router = Router(); -// FIXME: Rewrite to pull from Articles... -router.get('/', (req: Request, res: Response, next: NextFunction) => { - Article - .find() - .distinct('tagList') - .then((tagsArray: [string]) => { - return res.json({tags: tagsArray}); - }) - .catch(next); - -}); +router.get('/tags', getTags) export const TagRoutes: Router = router; diff --git a/src/routes/users-routes.ts b/src/routes/users-routes.ts index ac961f4..fe993aa 100644 --- a/src/routes/users-routes.ts +++ b/src/routes/users-routes.ts @@ -1,118 +1,122 @@ -import { NextFunction, Request, Response, Router } from 'express'; -import IUserModel, { User } from '../database/models/user.model'; -import passport from 'passport'; -import { authentication } from "../utilities/authentication"; +import { Router } from 'express'; +import { getUsers,registerUsers,postUsers,loginUsers } from '../controller/user-controller'; +// import IUserModel, { User } from '../database/models/user.model'; + const router: Router = Router(); /** * GET /api/user */ -router.get('/user', authentication.required, (req: Request, res: Response, next: NextFunction) => { +// router.get('/user', authentication.required, (req: Request, res: Response, next: NextFunction) => { - User - .findById(req.payload.id) - .then((user: IUserModel) => { - res.status(200).json({user: user.toAuthJSON()}); - } - ) - .catch(next); +// User +// .findById(req.payload.id) +// .then((user: IUserModel) => { +// res.status(200).json({user: user.toAuthJSON()}); +// } +// ) +// .catch(next); - } -); +// } +// ); -/** - * PUT /api/user - */ -router.put('/user', authentication.required, (req: Request, res: Response, next: NextFunction) => { +// /** +// * PUT /api/user +// */ +// router.put('/user', authentication.required, (req: Request, res: Response, next: NextFunction) => { - User - .findById(req.payload.id) - .then((user: IUserModel) => { +// User +// .findById(req.payload.id) +// .then((user: IUserModel) => { - if (!user) { - return res.sendStatus(401); - } +// if (!user) { +// return res.sendStatus(401); +// } - // Update only fields that have values: - // ISSUE: DRY out code? - if (typeof req.body.user.email !== 'undefined') { - user.email = req.body.user.email; - } - if (typeof req.body.user.username !== 'undefined') { - user.username = req.body.user.username; - } - if (typeof req.body.user.password !== 'undefined') { - user.setPassword(req.body.user.password); - } - if (typeof req.body.user.image !== 'undefined') { - user.image = req.body.user.image; - } - if (typeof req.body.user.bio !== 'undefined') { - user.bio = req.body.user.bio; - } +// // Update only fields that have values: +// // ISSUE: DRY out code? +// if (typeof req.body.user.email !== 'undefined') { +// user.email = req.body.user.email; +// } +// if (typeof req.body.user.username !== 'undefined') { +// user.username = req.body.user.username; +// } +// if (typeof req.body.user.password !== 'undefined') { +// user.setPassword(req.body.user.password); +// } +// if (typeof req.body.user.image !== 'undefined') { +// user.image = req.body.user.image; +// } +// if (typeof req.body.user.bio !== 'undefined') { +// user.bio = req.body.user.bio; +// } - return user.save().then(() => { - return res.json({user: user.toAuthJSON()}); - }); - }) - .catch(next); - } -); +// return user.save().then(() => { +// return res.json({user: user.toAuthJSON()}); +// }); +// }) +// .catch(next); +// } +// ); -/** - * POST /api/users - */ -router.post('/users', (req: Request, res: Response, next: NextFunction) => { +// /** +// * POST /api/users +// */ +// router.post('/users', (req: Request, res: Response, next: NextFunction) => { - const user: IUserModel = new User(); +// const user: IUserModel = new User(); - user.username = req.body.user.username; - user.email = req.body.user.email; - user.setPassword(req.body.user.password); - user.bio = ''; - user.image = ''; +// user.username = req.body.user.username; +// user.email = req.body.user.email; +// user.setPassword(req.body.user.password); +// user.bio = ''; +// user.image = ''; - return user.save() - .then(() => { - return res.json({user: user.toAuthJSON()}); - }) - .catch(next); +// return user.save() +// .then(() => { +// return res.json({user: user.toAuthJSON()}); +// }) +// .catch(next); -}); +// }); -// ISSUE: How does this work with the trailing (req, res, next)? -/** - * POST /api/users/login - */ -router.post('/users/login', (req: Request, res: Response, next: NextFunction) => { +// // ISSUE: How does this work with the trailing (req, res, next)? +// /** +// * POST /api/users/login +// */ +// router.post('/users/login', (req: Request, res: Response, next: NextFunction) => { - if (!req.body.user.email) { - return res.status(422).json({errors: {email: "Can't be blank"}}); - } +// if (!req.body.user.email) { +// return res.status(422).json({errors: {email: "Can't be blank"}}); +// } - if (!req.body.user.password) { - return res.status(422).json({errors: {password: "Can't be blank"}}); - } +// if (!req.body.user.password) { +// return res.status(422).json({errors: {password: "Can't be blank"}}); +// } - passport.authenticate('local', {session: false}, (err, user, info) => { - if (err) { - return next(err); - } +// passport.authenticate('local', {session: false}, (err, user, info) => { +// if (err) { +// return next(err); +// } - if (user) { - user.token = user.generateJWT(); - return res.json({user: user.toAuthJSON()}); +// if (user) { +// user.token = user.generateJWT(); +// return res.json({user: user.toAuthJSON()}); - } else { - return res.status(422).json(info); - } - })(req, res, next); +// } else { +// return res.status(422).json(info); +// } +// })(req, res, next); -}); +// }); +router.get('/users', getUsers) +router.put('/users', registerUsers) +router.post('/users', postUsers) +router.post('/users/login', loginUsers) export const UsersRoutes: Router = router;