├── .husky ├── .gitignore └── pre-commit ├── .prettierignore ├── Procfile ├── src ├── models │ ├── tag.model.ts │ ├── profile-response.model.ts │ ├── http-exception.model.ts │ ├── comment.model.ts │ ├── user.model.ts │ └── article.model.ts ├── utils │ ├── user-request.d.ts │ ├── token.utils.ts │ ├── profile.utils.ts │ └── auth.ts ├── selectors │ ├── user.selector.ts │ ├── profile.selector.ts │ ├── comment.selector.ts │ └── article.selector.ts ├── mappers │ ├── author.mapper.ts │ ├── user.mapper.ts │ ├── comment.mapper.ts │ └── article.mapper.ts ├── services │ ├── tag.service.ts │ ├── profile.service.ts │ ├── comment.service.ts │ ├── auth.service.ts │ └── article.service.ts ├── routes │ └── routes.ts ├── controllers │ ├── tag.controller.ts │ ├── profile.controller.ts │ ├── auth.controller.ts │ ├── comment.controller.ts │ └── article.controller.ts └── index.ts ├── media └── realworld.png ├── public └── images │ └── smiley-cyrus.jpeg ├── .prettierrc.json ├── prisma ├── migrations │ ├── migration_lock.toml │ ├── 20211106215130_default_image_url │ │ └── migration.sql │ ├── 20211115100640_updated_at │ │ └── migration.sql │ ├── 20211106214623_deprecated_previews │ │ └── migration.sql │ ├── 20211001195651_implicit_articles │ │ └── migration.sql │ └── 20210924222830_initial │ │ └── migration.sql ├── prisma-client.ts └── schema.prisma ├── jest.config.js ├── tests ├── services │ ├── tag.service.test.ts │ ├── article.service.test.ts │ ├── profile.service.test.ts │ └── auth.service.test.ts ├── prisma-mock.ts ├── mappers │ ├── author.mapper.test.ts │ ├── article.mapper.test.ts │ └── comment.mapper.test.ts └── utils │ └── profile.utils.test.ts ├── .github ├── dependabot.yml └── workflows │ └── ci.yaml ├── .gitignore ├── app.json ├── .eslintrc.json ├── LICENSE ├── README.md ├── package.json ├── CODE_OF_CONDUCT.md ├── tsconfig.json └── CONTRIBUTING.md /.husky/.gitignore: -------------------------------------------------------------------------------- 1 | _ 2 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | /dist 2 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: npm start 2 | 3 | release: npx prisma migrate deploy 4 | -------------------------------------------------------------------------------- /src/models/tag.model.ts: -------------------------------------------------------------------------------- 1 | export interface Tag { 2 | name: string; 3 | } 4 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | npx lint-staged 5 | -------------------------------------------------------------------------------- /media/realworld.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gothinkster/express-prisma-official-app/HEAD/media/realworld.png -------------------------------------------------------------------------------- /public/images/smiley-cyrus.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gothinkster/express-prisma-official-app/HEAD/public/images/smiley-cyrus.jpeg -------------------------------------------------------------------------------- /src/utils/user-request.d.ts: -------------------------------------------------------------------------------- 1 | declare namespace Express { 2 | export interface Request { 3 | user?: { 4 | username: string; 5 | }; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 100, 3 | "singleQuote": true, 4 | "trailingComma": "all", 5 | "bracketSpacing": true, 6 | "arrowParens": "avoid" 7 | } 8 | -------------------------------------------------------------------------------- /prisma/migrations/migration_lock.toml: -------------------------------------------------------------------------------- 1 | # Please do not edit this file manually 2 | # It should be added in your version-control system (i.e. Git) 3 | provider = "postgresql" -------------------------------------------------------------------------------- /src/models/profile-response.model.ts: -------------------------------------------------------------------------------- 1 | export interface ProfileResponse { 2 | username: string; 3 | bio: string | null; 4 | image: string | null; 5 | followedBy: any; 6 | } 7 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | clearMocks: true, 3 | preset: 'ts-jest', 4 | testEnvironment: 'node', 5 | setupFilesAfterEnv: ['/tests/prisma-mock.ts'], 6 | }; 7 | -------------------------------------------------------------------------------- /prisma/migrations/20211106215130_default_image_url/migration.sql: -------------------------------------------------------------------------------- 1 | -- AlterTable 2 | ALTER TABLE "User" ALTER COLUMN "image" SET DEFAULT E'https://api.realworld.io/images/smiley-cyrus.jpeg'; 3 | -------------------------------------------------------------------------------- /prisma/migrations/20211115100640_updated_at/migration.sql: -------------------------------------------------------------------------------- 1 | -- AlterTable 2 | ALTER TABLE "Article" ALTER COLUMN "updatedAt" DROP DEFAULT; 3 | 4 | -- AlterTable 5 | ALTER TABLE "Comment" ALTER COLUMN "updatedAt" DROP DEFAULT; 6 | -------------------------------------------------------------------------------- /tests/services/tag.service.test.ts: -------------------------------------------------------------------------------- 1 | describe('TagService', () => { 2 | describe('getTags', () => { 3 | // TODO : prismaMock.tag.groupBy.mockResolvedValue(mockedResponse) doesn't work 4 | test.todo('should return a list of strings'); 5 | }); 6 | }); 7 | -------------------------------------------------------------------------------- /src/selectors/user.selector.ts: -------------------------------------------------------------------------------- 1 | import { Prisma } from '@prisma/client'; 2 | 3 | export const userSelector = Prisma.validator()({ 4 | email: true, 5 | username: true, 6 | bio: true, 7 | image: true, 8 | }); 9 | 10 | export default userSelector; 11 | -------------------------------------------------------------------------------- /src/utils/token.utils.ts: -------------------------------------------------------------------------------- 1 | import jwt from 'jsonwebtoken'; 2 | import { User } from '../models/user.model'; 3 | 4 | const generateToken = (user: Partial): string => 5 | jwt.sign(user, process.env.JWT_SECRET || 'superSecret', { expiresIn: '60d' }); 6 | 7 | export default generateToken; 8 | -------------------------------------------------------------------------------- /src/models/http-exception.model.ts: -------------------------------------------------------------------------------- 1 | class HttpException extends Error { 2 | errorCode: number; 3 | 4 | constructor(errorCode: number, public readonly message: string | any) { 5 | super(message); 6 | this.errorCode = errorCode; 7 | } 8 | } 9 | 10 | export default HttpException; 11 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: github-actions 4 | directory: '/' 5 | schedule: 6 | interval: weekly 7 | open-pull-requests-limit: 10 8 | 9 | - package-ecosystem: npm 10 | directory: '/' 11 | schedule: 12 | interval: weekly 13 | open-pull-requests-limit: 10 14 | -------------------------------------------------------------------------------- /src/selectors/profile.selector.ts: -------------------------------------------------------------------------------- 1 | import { Prisma } from '@prisma/client'; 2 | 3 | const profileSelector = Prisma.validator()({ 4 | username: true, 5 | bio: true, 6 | image: true, 7 | followedBy: { 8 | select: { 9 | username: true, 10 | }, 11 | }, 12 | }); 13 | 14 | export default profileSelector; 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules 2 | /dist 3 | 4 | # Keep environment variables out of version control 5 | .env 6 | 7 | # IDEs and editors 8 | /.idea 9 | .project 10 | .classpath 11 | .c9/ 12 | *.launch 13 | .settings/ 14 | *.sublime-workspace 15 | 16 | # IDE - VSCode 17 | .vscode/* 18 | !.vscode/settings.json 19 | !.vscode/tasks.json 20 | !.vscode/launch.json 21 | !.vscode/extensions.json 22 | .history/* 23 | -------------------------------------------------------------------------------- /src/mappers/author.mapper.ts: -------------------------------------------------------------------------------- 1 | import { AuthorQueryResponse, Profile } from '../models/user.model'; 2 | 3 | const authorMapper = (author: AuthorQueryResponse, username?: string): Profile => ({ 4 | username: author.username, 5 | bio: author.bio, 6 | image: author.image, 7 | following: author.followedBy.some(follow => follow.username === username), 8 | }); 9 | 10 | export default authorMapper; 11 | -------------------------------------------------------------------------------- /src/mappers/user.mapper.ts: -------------------------------------------------------------------------------- 1 | import generateToken from '../utils/token.utils'; 2 | import { UserQueryResponse, UserResponse } from '../models/user.model'; 3 | 4 | export const userMapper = (user: UserQueryResponse): UserResponse => ({ 5 | email: user.email, 6 | username: user.username, 7 | bio: user.bio, 8 | image: user.bio, 9 | token: generateToken(user), 10 | }); 11 | 12 | export default userMapper; 13 | -------------------------------------------------------------------------------- /prisma/migrations/20211106214623_deprecated_previews/migration.sql: -------------------------------------------------------------------------------- 1 | -- RenameIndex 2 | ALTER INDEX "Article.slug_unique" RENAME TO "Article_slug_key"; 3 | 4 | -- RenameIndex 5 | ALTER INDEX "Tag.name_unique" RENAME TO "Tag_name_key"; 6 | 7 | -- RenameIndex 8 | ALTER INDEX "User.email_unique" RENAME TO "User_email_key"; 9 | 10 | -- RenameIndex 11 | ALTER INDEX "User.username_unique" RENAME TO "User_username_key"; 12 | -------------------------------------------------------------------------------- /src/selectors/comment.selector.ts: -------------------------------------------------------------------------------- 1 | import { Prisma } from '@prisma/client'; 2 | 3 | const commentSelector = Prisma.validator()({ 4 | id: true, 5 | createdAt: true, 6 | updatedAt: true, 7 | body: true, 8 | author: { 9 | select: { 10 | username: true, 11 | bio: true, 12 | image: true, 13 | followedBy: true, 14 | }, 15 | }, 16 | }); 17 | 18 | export default commentSelector; 19 | -------------------------------------------------------------------------------- /src/mappers/comment.mapper.ts: -------------------------------------------------------------------------------- 1 | import authorMapper from './author.mapper'; 2 | import { CommentQueryResponse, CommentResponse } from '../models/comment.model'; 3 | 4 | const commentMapper = (comment: CommentQueryResponse, username?: string): CommentResponse => ({ 5 | id: comment.id, 6 | createdAt: comment.createdAt, 7 | updatedAt: comment.updatedAt, 8 | body: comment.body, 9 | author: authorMapper(comment.author, username), 10 | }); 11 | 12 | export default commentMapper; 13 | -------------------------------------------------------------------------------- /src/models/comment.model.ts: -------------------------------------------------------------------------------- 1 | import { AuthorQueryResponse, Profile } from './user.model'; 2 | 3 | export interface CommentResponse { 4 | id: number; 5 | createdAt: Date; 6 | updatedAt: Date; 7 | body: string; 8 | author: Profile; 9 | } 10 | 11 | export interface CommentQueryResponse { 12 | id: number; 13 | createdAt: Date; 14 | updatedAt: Date; 15 | body: string; 16 | author: AuthorQueryResponse; 17 | } 18 | 19 | export type CommentListResponse = ReadonlyArray; 20 | -------------------------------------------------------------------------------- /app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "RealWorld API", 3 | "description": "Node / Express / Prisma API for RealWorld project", 4 | "keywords": ["node", "express", "prisma", "realworld"], 5 | "website": "https://gothinkster.github.io/realworld/", 6 | "repository": "https://github.com/gothinkster/realworld", 7 | "addons": ["heroku-postgresql"], 8 | "env": { 9 | "JWT_SECRET": { 10 | "description": "A secret key for verifying authenticated users", 11 | "generator": "secret" 12 | } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /tests/prisma-mock.ts: -------------------------------------------------------------------------------- 1 | import { PrismaClient } from '@prisma/client'; 2 | import { mockDeep, mockReset, DeepMockProxy } from 'jest-mock-extended'; 3 | 4 | import prisma from '../prisma/prisma-client'; 5 | 6 | jest.mock('../prisma/prisma-client', () => ({ 7 | __esModule: true, 8 | default: mockDeep(), 9 | })); 10 | 11 | const prismaMock = prisma as unknown as DeepMockProxy; 12 | 13 | beforeEach(() => { 14 | mockReset(prismaMock); 15 | }); 16 | 17 | export default prismaMock; 18 | -------------------------------------------------------------------------------- /src/services/tag.service.ts: -------------------------------------------------------------------------------- 1 | import prisma from '../../prisma/prisma-client'; 2 | 3 | const getTags = async (): Promise => { 4 | const tags = await prisma.tag.findMany({ 5 | where: { 6 | articles: { 7 | some: {}, 8 | }, 9 | }, 10 | select: { 11 | name: true, 12 | }, 13 | orderBy: { 14 | articles: { 15 | _count: 'desc', 16 | }, 17 | }, 18 | take: 10, 19 | }); 20 | 21 | return tags.map(tag => tag.name); 22 | }; 23 | 24 | export default getTags; 25 | -------------------------------------------------------------------------------- /src/utils/profile.utils.ts: -------------------------------------------------------------------------------- 1 | import { Profile, User } from '../models/user.model'; 2 | import { ProfileResponse } from '../models/profile-response.model'; 3 | 4 | const profileMapper = (profile: ProfileResponse, username: string | undefined): Profile => ({ 5 | username: profile.username, 6 | bio: profile.bio, 7 | image: profile.image, 8 | following: username 9 | ? profile?.followedBy.some( 10 | (followingUser: Pick) => followingUser.username === username, 11 | ) 12 | : false, 13 | }); 14 | 15 | export default profileMapper; 16 | -------------------------------------------------------------------------------- /prisma/prisma-client.ts: -------------------------------------------------------------------------------- 1 | import { PrismaClient } from '@prisma/client'; 2 | 3 | // add prisma to the NodeJS global type 4 | // TODO : downgraded @types/node to 15.14.1 to avoid error on NodeJS.Global 5 | interface CustomNodeJsGlobal extends NodeJS.Global { 6 | prisma: PrismaClient; 7 | } 8 | 9 | // Prevent multiple instances of Prisma Client in development 10 | declare const global: CustomNodeJsGlobal; 11 | 12 | const prisma = global.prisma || new PrismaClient(); 13 | 14 | if (process.env.NODE_ENV === 'development') { 15 | global.prisma = prisma; 16 | } 17 | 18 | export default prisma; 19 | -------------------------------------------------------------------------------- /src/routes/routes.ts: -------------------------------------------------------------------------------- 1 | import { Router } from 'express'; 2 | import tagsController from '../controllers/tag.controller'; 3 | import articlesController from '../controllers/article.controller'; 4 | import authController from '../controllers/auth.controller'; 5 | import profileController from '../controllers/profile.controller'; 6 | import commentController from '../controllers/comment.controller'; 7 | 8 | const api = Router() 9 | .use(tagsController) 10 | .use(articlesController) 11 | .use(commentController) 12 | .use(profileController) 13 | .use(authController); 14 | 15 | export default Router().use('/api', api); 16 | -------------------------------------------------------------------------------- /src/controllers/tag.controller.ts: -------------------------------------------------------------------------------- 1 | import { NextFunction, Request, Response, Router } from 'express'; 2 | import auth from '../utils/auth'; 3 | import getTags from '../services/tag.service'; 4 | 5 | const router = Router(); 6 | 7 | /** 8 | * Get top 10 popular tags 9 | * @auth optional 10 | * @route {GET} /api/tags 11 | * @returns tags list of tag names 12 | */ 13 | router.get('/tags', auth.optional, async (req: Request, res: Response, next: NextFunction) => { 14 | try { 15 | const tags = await getTags(); 16 | res.json({ tags }); 17 | } catch (error) { 18 | next(error); 19 | } 20 | }); 21 | 22 | export default router; 23 | -------------------------------------------------------------------------------- /src/mappers/article.mapper.ts: -------------------------------------------------------------------------------- 1 | import { ArticleQueryResponse, ArticleResponse } from '../models/article.model'; 2 | import authorMapper from './author.mapper'; 3 | 4 | const articleMapper = (article: ArticleQueryResponse, username?: string): ArticleResponse => ({ 5 | slug: article.slug, 6 | title: article.title, 7 | description: article.description, 8 | body: article.body, 9 | tagList: article.tagList.map(tag => tag.name), 10 | createdAt: article.createdAt, 11 | updatedAt: article.updatedAt, 12 | favorited: article.favoritedBy.some(item => item.username === username), 13 | favoritesCount: article.favoritedBy.length, 14 | author: authorMapper(article.author, username), 15 | }); 16 | 17 | export default articleMapper; 18 | -------------------------------------------------------------------------------- /src/selectors/article.selector.ts: -------------------------------------------------------------------------------- 1 | import { Prisma } from '@prisma/client'; 2 | 3 | const articleSelector = Prisma.validator()({ 4 | slug: true, 5 | title: true, 6 | description: true, 7 | body: true, 8 | createdAt: true, 9 | updatedAt: true, 10 | tagList: { 11 | select: { 12 | name: true, 13 | }, 14 | }, 15 | author: { 16 | select: { 17 | username: true, 18 | bio: true, 19 | image: true, 20 | followedBy: true, 21 | }, 22 | }, 23 | favoritedBy: { 24 | select: { 25 | username: true, 26 | }, 27 | }, 28 | _count: { 29 | select: { 30 | favoritedBy: true, 31 | }, 32 | }, 33 | }); 34 | 35 | export default articleSelector; 36 | -------------------------------------------------------------------------------- /src/utils/auth.ts: -------------------------------------------------------------------------------- 1 | const jwt = require('express-jwt'); 2 | 3 | const getTokenFromHeaders = (req: { headers: { authorization: string } }): string | null => { 4 | if ( 5 | (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Token') || 6 | (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') 7 | ) { 8 | return req.headers.authorization.split(' ')[1]; 9 | } 10 | return null; 11 | }; 12 | 13 | const auth = { 14 | required: jwt({ 15 | secret: process.env.JWT_SECRET || 'superSecret', 16 | getToken: getTokenFromHeaders, 17 | algorithms: ['HS256'], 18 | }), 19 | optional: jwt({ 20 | secret: process.env.JWT_SECRET || 'superSecret', 21 | credentialsRequired: false, 22 | getToken: getTokenFromHeaders, 23 | algorithms: ['HS256'], 24 | }), 25 | }; 26 | 27 | export default auth; 28 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": true, 4 | "es2021": true, 5 | "jest": true 6 | }, 7 | "extends": ["airbnb-base", "prettier"], 8 | "globals": { 9 | "NodeJS": true 10 | }, 11 | "parser": "@typescript-eslint/parser", 12 | "parserOptions": { 13 | "ecmaVersion": 12, 14 | "sourceType": "module" 15 | }, 16 | "plugins": ["@typescript-eslint"], 17 | "rules": { 18 | "import/extensions": [ 19 | "error", 20 | "ignorePackages", 21 | { 22 | "ts": "never" 23 | } 24 | ], 25 | "no-underscore-dangle": ["error", { "allow": ["_count"] }], 26 | "no-console": ["error", { "allow": ["info"] }], 27 | "import/no-extraneous-dependencies": ["error", { "devDependencies": ["tests/prisma-mock.ts"] }] 28 | }, 29 | "settings": { 30 | "import/resolver": { 31 | "node": { 32 | "paths": ["src"], 33 | "extensions": [".js", ".ts", ".d.ts", ".tsx"] 34 | } 35 | } 36 | }, 37 | "ignorePatterns": ["*.d.ts"] 38 | } 39 | -------------------------------------------------------------------------------- /src/models/user.model.ts: -------------------------------------------------------------------------------- 1 | export interface User { 2 | username: string; 3 | email: string; 4 | password: string; 5 | bio: string | null; 6 | image: string | null; 7 | // eslint-disable-next-line no-use-before-define 8 | followedBy: ReadonlyArray; 9 | token: string; 10 | following: boolean; 11 | } 12 | 13 | export type UserCreatePayload = Pick; 14 | 15 | export type UserUpdatePayload = Pick; 16 | 17 | export type UserLoginPayload = Pick; 18 | 19 | export type UserQueryResponse = Pick; 20 | 21 | export type UserResponse = Pick; 22 | 23 | export type AuthorQueryResponse = Pick; 24 | 25 | export type FollowersQueryReponse = Pick; 26 | 27 | export type Profile = Pick; 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import express, { NextFunction, Request, Response } from 'express'; 2 | import cors from 'cors'; 3 | import bodyParser from 'body-parser'; 4 | import routes from './routes/routes'; 5 | import HttpException from './models/http-exception.model'; 6 | 7 | const app = express(); 8 | 9 | /** 10 | * App Configuration 11 | */ 12 | 13 | app.use(cors()); 14 | app.use(bodyParser.json()); 15 | app.use(bodyParser.urlencoded({ extended: true })); 16 | app.use(routes); 17 | 18 | // Serves images 19 | app.use(express.static('public')); 20 | 21 | app.get('/', (req: Request, res: Response) => { 22 | res.json({ status: 'API is running on /api' }); 23 | }); 24 | 25 | /* eslint-disable */ 26 | app.use((err: Error | HttpException, req: Request, res: Response, next: NextFunction) => { 27 | // @ts-ignore 28 | if (err && err.errorCode) { 29 | // @ts-ignore 30 | res.status(err.errorCode).json(err.message); 31 | } else if (err) { 32 | res.status(500).json(err.message); 33 | } 34 | }); 35 | 36 | /** 37 | * Server activation 38 | */ 39 | 40 | const PORT = process.env.PORT || 3000; 41 | app.listen(PORT, () => { 42 | console.info(`server up on port ${PORT}`); 43 | }); 44 | -------------------------------------------------------------------------------- /src/models/article.model.ts: -------------------------------------------------------------------------------- 1 | import { Tag } from './tag.model'; 2 | import { AuthorQueryResponse, Profile, FollowersQueryReponse } from './user.model'; 3 | 4 | export interface ArticleCreatePayload { 5 | title: string; 6 | description: string; 7 | body: string; 8 | tagList: ReadonlyArray; 9 | } 10 | 11 | export interface ArticleFindQuery { 12 | author?: string; 13 | tag?: string; 14 | favorited?: string; 15 | offset?: string; 16 | limit?: string; 17 | } 18 | 19 | export interface ArticleQueryResponse { 20 | slug: string; 21 | title: string; 22 | description: string; 23 | body: string; 24 | tagList: ReadonlyArray; 25 | createdAt: Date; 26 | updatedAt: Date; 27 | favoritedBy: ReadonlyArray; 28 | author: AuthorQueryResponse; 29 | } 30 | 31 | export interface ArticleResponse { 32 | slug: string; 33 | title: string; 34 | description: string; 35 | body: string; 36 | tagList: ReadonlyArray; 37 | createdAt: Date; 38 | updatedAt: Date; 39 | favorited: boolean; 40 | favoritesCount: number; 41 | author: Profile; 42 | } 43 | 44 | export interface ArticleListResponse { 45 | articles: ReadonlyArray; 46 | articlesCount: number; 47 | } 48 | -------------------------------------------------------------------------------- /tests/mappers/author.mapper.test.ts: -------------------------------------------------------------------------------- 1 | import { AuthorQueryResponse, Profile } from '../../src/models/user.model'; 2 | import authorMapper from '../../src/mappers/author.mapper'; 3 | 4 | describe('AuthorMapper', () => { 5 | test('should return an author when logged out', () => { 6 | const authorQueryResponse: AuthorQueryResponse = { 7 | username: '', 8 | image: '', 9 | bio: '', 10 | followedBy: [], 11 | }; 12 | 13 | const authorResponse: Profile = { 14 | username: '', 15 | image: '', 16 | bio: '', 17 | following: false, 18 | }; 19 | 20 | expect(authorMapper(authorQueryResponse)).toEqual(authorResponse); 21 | }); 22 | 23 | test('should return an author when logged out', () => { 24 | const authorQueryResponse: AuthorQueryResponse = { 25 | username: '', 26 | image: '', 27 | bio: '', 28 | followedBy: [ 29 | { 30 | username: 'Gerome', 31 | }, 32 | ], 33 | }; 34 | 35 | const authorResponse: Profile = { 36 | username: '', 37 | image: '', 38 | bio: '', 39 | following: true, 40 | }; 41 | 42 | expect(authorMapper(authorQueryResponse, 'Gerome')).toEqual(authorResponse); 43 | }); 44 | }); 45 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | branches: 8 | - '**' 9 | 10 | jobs: 11 | run_tests: 12 | runs-on: ubuntu-latest 13 | 14 | strategy: 15 | matrix: 16 | node-version: [12.x] 17 | 18 | steps: 19 | - uses: actions/checkout@v2 20 | - uses: actions/setup-node@v2.4.1 21 | with: 22 | node-version: '12' 23 | - name: Cache node modules 24 | uses: actions/cache@v2 25 | env: 26 | cache-name: cache-node-modules 27 | with: 28 | path: ~/.npm 29 | key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} 30 | restore-keys: | 31 | ${{ runner.os }}-build-${{ env.cache-name }}- 32 | ${{ runner.os }}-build- 33 | ${{ runner.os }}- 34 | - name: Install dependencies 35 | run: npm ci --no-audit --prefer-offline --progress=false 36 | - name: Check prettier 37 | run: npm run prettier:check 38 | - name: Check ESLinter 39 | run: npm run lint:check 40 | - name: Check unit tests 41 | run: npm run test --ci --lastCommit --maxWorkers=50% 42 | env: 43 | CI: true 44 | -------------------------------------------------------------------------------- /tests/mappers/article.mapper.test.ts: -------------------------------------------------------------------------------- 1 | import { ArticleQueryResponse, ArticleResponse } from '../../src/models/article.model'; 2 | import articleMapper from '../../src/mappers/article.mapper'; 3 | 4 | describe('ArticleMapper', () => { 5 | test('should return a formatted article', () => { 6 | const articleQueryResponse: ArticleQueryResponse = { 7 | author: { 8 | username: 'Gerome', 9 | image: '', 10 | bio: '', 11 | followedBy: [], 12 | }, 13 | body: '', 14 | createdAt: new Date(), 15 | description: '', 16 | favoritedBy: [], 17 | slug: '', 18 | tagList: [], 19 | title: '', 20 | updatedAt: new Date(), 21 | }; 22 | 23 | const articleResponse: ArticleResponse = { 24 | author: { 25 | username: 'Gerome', 26 | image: '', 27 | bio: '', 28 | following: false, 29 | }, 30 | body: '', 31 | createdAt: articleQueryResponse.createdAt, 32 | description: '', 33 | favorited: false, 34 | favoritesCount: 0, 35 | slug: '', 36 | tagList: [], 37 | title: '', 38 | updatedAt: articleQueryResponse.updatedAt, 39 | }; 40 | 41 | expect(articleMapper(articleQueryResponse)).toEqual(articleResponse); 42 | }); 43 | }); 44 | -------------------------------------------------------------------------------- /prisma/migrations/20211001195651_implicit_articles/migration.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Warnings: 3 | 4 | - You are about to drop the `ArticleTags` table. If the table is not empty, all the data it contains will be lost. 5 | - A unique constraint covering the columns `[name]` on the table `Tag` will be added. If there are existing duplicate values, this will fail. 6 | 7 | */ 8 | -- DropForeignKey 9 | ALTER TABLE "ArticleTags" DROP CONSTRAINT "ArticleTags_articleId_fkey"; 10 | 11 | -- DropForeignKey 12 | ALTER TABLE "ArticleTags" DROP CONSTRAINT "ArticleTags_tagId_fkey"; 13 | 14 | -- DropTable 15 | DROP TABLE "ArticleTags"; 16 | 17 | -- CreateTable 18 | CREATE TABLE "_ArticleToTag" ( 19 | "A" INTEGER NOT NULL, 20 | "B" INTEGER NOT NULL 21 | ); 22 | 23 | -- CreateIndex 24 | CREATE UNIQUE INDEX "_ArticleToTag_AB_unique" ON "_ArticleToTag"("A", "B"); 25 | 26 | -- CreateIndex 27 | CREATE INDEX "_ArticleToTag_B_index" ON "_ArticleToTag"("B"); 28 | 29 | -- CreateIndex 30 | CREATE UNIQUE INDEX "Tag.name_unique" ON "Tag"("name"); 31 | 32 | -- AddForeignKey 33 | ALTER TABLE "_ArticleToTag" ADD FOREIGN KEY ("A") REFERENCES "Article"("id") ON DELETE CASCADE ON UPDATE CASCADE; 34 | 35 | -- AddForeignKey 36 | ALTER TABLE "_ArticleToTag" ADD FOREIGN KEY ("B") REFERENCES "Tag"("id") ON DELETE CASCADE ON UPDATE CASCADE; 37 | -------------------------------------------------------------------------------- /src/services/profile.service.ts: -------------------------------------------------------------------------------- 1 | import prisma from '../../prisma/prisma-client'; 2 | import profileMapper from '../utils/profile.utils'; 3 | import HttpException from '../models/http-exception.model'; 4 | import { findUserIdByUsername } from './auth.service'; 5 | import { Profile } from '../models/user.model'; 6 | import profileSelector from '../selectors/profile.selector'; 7 | 8 | export const getProfile = async ( 9 | profileUsername: string | undefined, 10 | username: string | undefined, 11 | ): Promise => { 12 | const profile = await prisma.user.findUnique({ 13 | where: { 14 | username: profileUsername, 15 | }, 16 | select: profileSelector, 17 | }); 18 | 19 | if (!profile) { 20 | throw new HttpException(404, {}); 21 | } 22 | 23 | return profileMapper(profile, username); 24 | }; 25 | 26 | export const followUser = async (profileUsername: string, username: string): Promise => { 27 | const id = await findUserIdByUsername(username); 28 | 29 | const profile = await prisma.user.update({ 30 | where: { 31 | username: profileUsername, 32 | }, 33 | data: { 34 | followedBy: { 35 | connect: { 36 | id, 37 | }, 38 | }, 39 | }, 40 | select: profileSelector, 41 | }); 42 | 43 | return profileMapper(profile, username); 44 | }; 45 | 46 | export const unfollowUser = async (profileUsername: string, username: string): Promise => { 47 | const id = await findUserIdByUsername(username); 48 | 49 | const profile = await prisma.user.update({ 50 | where: { 51 | username: profileUsername, 52 | }, 53 | data: { 54 | followedBy: { 55 | disconnect: { 56 | id, 57 | }, 58 | }, 59 | }, 60 | select: profileSelector, 61 | }); 62 | 63 | return profileMapper(profile, username); 64 | }; 65 | -------------------------------------------------------------------------------- /src/controllers/profile.controller.ts: -------------------------------------------------------------------------------- 1 | import { NextFunction, Request, Response, Router } from 'express'; 2 | import auth from '../utils/auth'; 3 | import { followUser, getProfile, unfollowUser } from '../services/profile.service'; 4 | 5 | const router = Router(); 6 | 7 | /** 8 | * Get profile 9 | * @auth optional 10 | * @route {GET} /profiles/:username 11 | * @param username string 12 | * @returns Profile profile of an user 13 | */ 14 | router.get( 15 | '/profiles/:username', 16 | auth.optional, 17 | async (req: Request, res: Response, next: NextFunction) => { 18 | try { 19 | const profile = await getProfile(req.params.username, req.user?.username); 20 | res.json({ profile }); 21 | } catch (error) { 22 | next(error); 23 | } 24 | }, 25 | ); 26 | 27 | /** 28 | * Follow user 29 | * @auth required 30 | * @route {POST} /profiles/:username/follow 31 | * @param username string 32 | * @returns Profile profile of an user 33 | */ 34 | router.post( 35 | '/profiles/:username/follow', 36 | auth.required, 37 | async (req: Request, res: Response, next: NextFunction) => { 38 | try { 39 | const profile = await followUser(req.params?.username, req.user!.username); 40 | res.json({ profile }); 41 | } catch (error) { 42 | next(error); 43 | } 44 | }, 45 | ); 46 | 47 | /** 48 | * Unfollow user 49 | * @auth required 50 | * @route {DELETE} /profiles/:username/follow 51 | * @param username string 52 | * @returns profiles 53 | */ 54 | router.delete( 55 | '/profiles/:username/follow', 56 | auth.required, 57 | async (req: Request, res: Response, next: NextFunction) => { 58 | try { 59 | const profile = await unfollowUser(req.params.username, req.user!.username); 60 | res.json({ profile }); 61 | } catch (error) { 62 | next(error); 63 | } 64 | }, 65 | ); 66 | 67 | export default router; 68 | -------------------------------------------------------------------------------- /src/controllers/auth.controller.ts: -------------------------------------------------------------------------------- 1 | import { NextFunction, Request, Response, Router } from 'express'; 2 | import auth from '../utils/auth'; 3 | import { createUser, getCurrentUser, login, updateUser } from '../services/auth.service'; 4 | 5 | const router = Router(); 6 | 7 | /** 8 | * Create an user 9 | * @auth none 10 | * @route {POST} /users 11 | * @bodyparam user User 12 | * @returns user User 13 | */ 14 | router.post('/users', async (req: Request, res: Response, next: NextFunction) => { 15 | try { 16 | const user = await createUser(req.body.user); 17 | res.json({ user }); 18 | } catch (error) { 19 | next(error); 20 | } 21 | }); 22 | 23 | /** 24 | * Login 25 | * @auth none 26 | * @route {POST} /users/login 27 | * @bodyparam user User 28 | * @returns user User 29 | */ 30 | router.post('/users/login', async (req: Request, res: Response, next: NextFunction) => { 31 | try { 32 | const user = await login(req.body.user); 33 | res.json({ user }); 34 | } catch (error) { 35 | next(error); 36 | } 37 | }); 38 | 39 | /** 40 | * Get current user 41 | * @auth required 42 | * @route {GET} /user 43 | * @returns user User 44 | */ 45 | router.get('/user', auth.required, async (req: Request, res: Response, next: NextFunction) => { 46 | try { 47 | const user = await getCurrentUser(req.user!.username); 48 | res.json({ user }); 49 | } catch (error) { 50 | next(error); 51 | } 52 | }); 53 | 54 | /** 55 | * Update user 56 | * @auth required 57 | * @route {PUT} /user 58 | * @bodyparam user User 59 | * @returns user User 60 | */ 61 | router.put('/user', auth.required, async (req: Request, res: Response, next: NextFunction) => { 62 | try { 63 | const user = await updateUser(req.body.user, req.user!.username); 64 | res.json({ user }); 65 | } catch (error) { 66 | next(error); 67 | } 68 | }); 69 | 70 | export default router; 71 | -------------------------------------------------------------------------------- /src/services/comment.service.ts: -------------------------------------------------------------------------------- 1 | import prisma from '../../prisma/prisma-client'; 2 | import HttpException from '../models/http-exception.model'; 3 | import { findUserIdByUsername } from './auth.service'; 4 | import commentMapper from '../mappers/comment.mapper'; 5 | import { CommentListResponse, CommentResponse } from '../models/comment.model'; 6 | import commentSelector from '../selectors/comment.selector'; 7 | 8 | export const getCommentsByArticle = async ( 9 | slug: string, 10 | username: string | undefined, 11 | ): Promise => { 12 | const comments = await prisma.comment.findMany({ 13 | where: { 14 | article: { 15 | slug, 16 | }, 17 | }, 18 | select: commentSelector, 19 | }); 20 | 21 | return comments.map(comment => commentMapper(comment, username)); 22 | }; 23 | 24 | export const addComment = async ( 25 | body: string, 26 | slug: string, 27 | username: string, 28 | ): Promise => { 29 | if (!body) { 30 | throw new HttpException(422, { errors: { body: ["can't be blank"] } }); 31 | } 32 | 33 | const id = await findUserIdByUsername(username); 34 | 35 | const article = await prisma.article.findUnique({ 36 | where: { 37 | slug, 38 | }, 39 | select: { 40 | id: true, 41 | }, 42 | }); 43 | 44 | const comment = await prisma.comment.create({ 45 | data: { 46 | body, 47 | article: { 48 | connect: { 49 | id: article?.id, 50 | }, 51 | }, 52 | author: { 53 | connect: { 54 | id, 55 | }, 56 | }, 57 | }, 58 | select: commentSelector, 59 | }); 60 | 61 | return commentMapper(comment, username); 62 | }; 63 | 64 | export const deleteComment = async (id: number): Promise => { 65 | await prisma.comment.delete({ 66 | where: { 67 | id, 68 | }, 69 | }); 70 | }; 71 | -------------------------------------------------------------------------------- /tests/mappers/comment.mapper.test.ts: -------------------------------------------------------------------------------- 1 | import { CommentQueryResponse, CommentResponse } from '../../src/models/comment.model'; 2 | import commentMapper from '../../src/mappers/comment.mapper'; 3 | 4 | describe('CommentMapper', () => { 5 | test('should return a comment when logged out', () => { 6 | const commentQueryResponse: CommentQueryResponse = { 7 | id: 0, 8 | author: { 9 | username: '', 10 | image: '', 11 | bio: '', 12 | followedBy: [], 13 | }, 14 | body: '', 15 | createdAt: new Date(), 16 | updatedAt: new Date(), 17 | }; 18 | 19 | const commentResponse: CommentResponse = { 20 | id: 0, 21 | createdAt: commentQueryResponse.createdAt, 22 | updatedAt: commentQueryResponse.updatedAt, 23 | body: '', 24 | author: { 25 | username: '', 26 | image: '', 27 | bio: '', 28 | following: false, 29 | }, 30 | }; 31 | 32 | expect(commentMapper(commentQueryResponse)).toEqual(commentResponse); 33 | }); 34 | 35 | test('should return a comment of an user who follow', () => { 36 | const commentQueryResponse: CommentQueryResponse = { 37 | id: 0, 38 | author: { 39 | username: '', 40 | image: '', 41 | bio: '', 42 | followedBy: [ 43 | { 44 | username: 'Gerome', 45 | }, 46 | ], 47 | }, 48 | body: '', 49 | createdAt: new Date(), 50 | updatedAt: new Date(), 51 | }; 52 | 53 | const commentResponse: CommentResponse = { 54 | id: 0, 55 | createdAt: commentQueryResponse.createdAt, 56 | updatedAt: commentQueryResponse.updatedAt, 57 | body: '', 58 | author: { 59 | username: '', 60 | image: '', 61 | bio: '', 62 | following: true, 63 | }, 64 | }; 65 | 66 | expect(commentMapper(commentQueryResponse, 'Gerome')).toEqual(commentResponse); 67 | }); 68 | }); 69 | -------------------------------------------------------------------------------- /prisma/schema.prisma: -------------------------------------------------------------------------------- 1 | // This is your Prisma schema file, 2 | // learn more about it in the docs: https://pris.ly/d/prisma-schema 3 | 4 | datasource db { 5 | provider = "postgresql" 6 | url = env("DATABASE_URL") 7 | } 8 | 9 | generator client { 10 | provider = "prisma-client-js" 11 | } 12 | 13 | model Article { 14 | id Int @id @default(autoincrement()) 15 | slug String @unique 16 | title String 17 | description String 18 | body String 19 | createdAt DateTime @default(now()) 20 | updatedAt DateTime @updatedAt 21 | tagList Tag[] 22 | author User @relation("UserArticles", fields: [authorId], references: [id], onDelete: Cascade) 23 | authorId Int 24 | favoritedBy User[] @relation("UserFavorites", references: [id]) 25 | comments Comment[] 26 | } 27 | 28 | model Comment { 29 | id Int @id @default(autoincrement()) 30 | createdAt DateTime @default(now()) 31 | updatedAt DateTime @updatedAt 32 | body String 33 | article Article @relation(fields: [articleId], references: [id], onDelete: Cascade) 34 | articleId Int 35 | author User @relation(fields: [authorId], references: [id], onDelete: Cascade) 36 | authorId Int 37 | } 38 | 39 | model Tag { 40 | id Int @id @default(autoincrement()) 41 | name String @unique 42 | articles Article[] 43 | } 44 | 45 | model User { 46 | id Int @id @default(autoincrement()) 47 | email String @unique 48 | username String @unique 49 | password String 50 | image String? @default("https://api.realworld.io/images/smiley-cyrus.jpeg") 51 | bio String? 52 | articles Article[] @relation("UserArticles") 53 | favorites Article[] @relation("UserFavorites", references: [id]) 54 | followedBy User[] @relation("UserFollows", references: [id]) 55 | following User[] @relation("UserFollows", references: [id]) 56 | comments Comment[] 57 | } 58 | -------------------------------------------------------------------------------- /src/controllers/comment.controller.ts: -------------------------------------------------------------------------------- 1 | import { NextFunction, Request, Response, Router } from 'express'; 2 | import auth from '../utils/auth'; 3 | import { addComment, deleteComment, getCommentsByArticle } from '../services/comment.service'; 4 | 5 | const router = Router(); 6 | 7 | /** 8 | * Get comments from an article 9 | * @auth optional 10 | * @route {GET} /articles/:slug/comments 11 | * @param slug slug of the article (based on the title) 12 | * @returns comments list of comments 13 | */ 14 | router.get( 15 | '/articles/:slug/comments', 16 | auth.optional, 17 | async (req: Request, res: Response, next: NextFunction) => { 18 | try { 19 | const comments = await getCommentsByArticle(req.params.slug, req.user?.username); 20 | res.json({ comments }); 21 | } catch (error) { 22 | next(error); 23 | } 24 | }, 25 | ); 26 | 27 | /** 28 | * Add comment to article 29 | * @auth required 30 | * @route {POST} /articles/:slug/comments 31 | * @param slug slug of the article (based on the title) 32 | * @bodyparam body content of the comment 33 | * @returns comment created comment 34 | */ 35 | router.post( 36 | '/articles/:slug/comments', 37 | auth.required, 38 | async (req: Request, res: Response, next: NextFunction) => { 39 | try { 40 | const comment = await addComment(req.body.comment.body, req.params.slug, req.user!.username); 41 | res.json({ comment }); 42 | } catch (error) { 43 | next(error); 44 | } 45 | }, 46 | ); 47 | 48 | /** 49 | * Delete comment 50 | * @auth required 51 | * @route {DELETE} /articles/:slug/comments/:id 52 | * @param slug slug of the article (based on the title) 53 | * @param id id of the comment 54 | */ 55 | router.delete( 56 | '/articles/:slug/comments/:id', 57 | auth.required, 58 | async (req: Request, res: Response, next: NextFunction) => { 59 | try { 60 | await deleteComment(Number(req.params.id)); 61 | res.sendStatus(204); 62 | } catch (error) { 63 | next(error); 64 | } 65 | }, 66 | ); 67 | 68 | export default router; 69 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ![Node Example App](media/realworld.png) 2 | 3 | > Official NodeJS RealWorld codebase (V2) 4 | 5 | **WORK IN PROGRESS** 6 | 7 | # Deploy to Heroku 8 | 9 | [![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy) 10 | 11 | # Getting started 12 | 13 | ### Clone the repository 14 | 15 | run `git clone https://github.com/gothinkster/node-express-prisma-v1-official-app.git` 16 | 17 | ### Install the dependancies 18 | 19 | > [NodeJS](https://nodejs.dev/) is required 20 | 21 | ``` 22 | cd node-express-prisma-v1-official-app 23 | npm install 24 | ``` 25 | 26 | ### Download pgAdmin for PostgreSQL 27 | 28 | [PostgreSQL](https://www.postgresql.org/download/) downloads page 29 | 30 | ### Create a server 31 | 32 | run **pgAdmin** 33 | create a server (Object/Create/Server) 34 | required fields: 35 | 36 | - name 37 | - HOST name/address 38 | 39 | ### Connect the created server 40 | 41 | create a _.env_ file at the root of the project 42 | populate it with the url of your database 43 | 44 | ``` 45 | DATABASE_URL="postgresql://:@:/?schema=public" 46 | ``` 47 | 48 | ### Run the project locally 49 | 50 | run `npm run dev` 51 | 52 | ## Advanced usage 53 | 54 | ### Prisma 55 | 56 | ### Format the Prisma schema 57 | 58 | ```bash 59 | npm run prisma:format 60 | ``` 61 | 62 | ### Migrate the SQL schema 63 | 64 | ```bash 65 | prisma migrate dev --name added_job_title 66 | ``` 67 | 68 | ### Update the Prisma Client 69 | 70 | ```bash 71 | npm run prisma:generate 72 | ``` 73 | 74 | _with watch option_ 75 | 76 | ```bash 77 | npm run prisma:generate:watch 78 | ``` 79 | 80 | ### Seed the database 81 | 82 | ```bash 83 | npm run prisma:seed 84 | ``` 85 | 86 | ### Launch Prisma Studio 87 | 88 | ```bash 89 | npm run prisma:studio 90 | ``` 91 | 92 | ### Reset the database 93 | 94 | - Drop the database 95 | - Create a new database 96 | - Apply migrations 97 | - Seed the database with data 98 | 99 | ```bash 100 | npm run prisma:reset 101 | ``` 102 | -------------------------------------------------------------------------------- /tests/utils/profile.utils.test.ts: -------------------------------------------------------------------------------- 1 | import profileMapper from '../../src/utils/profile.utils'; 2 | 3 | describe('ProfileUtils', () => { 4 | describe('profileMapper', () => { 5 | test('should return a profile', () => { 6 | // Given 7 | const profile = { 8 | username: 'RealWorld', 9 | bio: 'My happy life', 10 | image: null, 11 | followedBy: [], 12 | }; 13 | const username = 'RealWorld'; 14 | 15 | // When 16 | const expected = { 17 | username: 'RealWorld', 18 | bio: 'My happy life', 19 | image: null, 20 | following: false, 21 | }; 22 | 23 | // Then 24 | expect(profileMapper(profile, username)).toEqual(expected); 25 | }); 26 | 27 | test('should return a profile followed by the user', () => { 28 | // Given 29 | const profile = { 30 | username: 'RealWorld', 31 | bio: 'My happy life', 32 | image: null, 33 | followedBy: [ 34 | { 35 | username: 'RealWorld', 36 | }, 37 | ], 38 | }; 39 | const username = 'RealWorld'; 40 | 41 | // When 42 | const expected = { 43 | username: 'RealWorld', 44 | bio: 'My happy life', 45 | image: null, 46 | following: true, 47 | }; 48 | 49 | // Then 50 | expect(profileMapper(profile, username)).toEqual(expected); 51 | }); 52 | 53 | test('should return a profile not followed by the user', () => { 54 | // Given 55 | const profile = { 56 | username: 'RealWorld', 57 | bio: 'My happy life', 58 | image: null, 59 | followedBy: [ 60 | { 61 | username: 'NotRealWorld', 62 | }, 63 | ], 64 | }; 65 | const username = 'RealWorld'; 66 | 67 | // When 68 | const expected = { 69 | username: 'RealWorld', 70 | bio: 'My happy life', 71 | image: null, 72 | following: false, 73 | }; 74 | 75 | // Then 76 | expect(profileMapper(profile, username)).toEqual(expected); 77 | }); 78 | }); 79 | }); 80 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "express-prisma-realworld-official-app", 3 | "version": "1.0.1", 4 | "description": "Node.js, Express.js & Prisma RealWorld official app", 5 | "main": "index.js", 6 | "scripts": { 7 | "postinstall": "tsc", 8 | "test": "jest -i", 9 | "dev": "ts-node-dev --respawn --pretty --transpile-only src/index.ts dev", 10 | "start": "node dist/src/index.js", 11 | "prisma:migrate": "prisma migrate dev --skip-seed", 12 | "prisma:format": "prisma format", 13 | "prisma:generate": "prisma generate", 14 | "prisma:generate:watch": "prisma generate --watch", 15 | "prisma:seed": "prisma db seed --preview-feature", 16 | "prisma:studio": "prisma studio", 17 | "prisma:reset": "prisma migrate reset", 18 | "prettier:write": "npx prettier --write .", 19 | "prettier:check": "npx prettier --check .", 20 | "lint:check": "npx eslint src/**/*.ts", 21 | "lint:fix": "npx eslint --fix src/**/*.ts", 22 | "prepare": "husky install" 23 | }, 24 | "keywords": [ 25 | "node", 26 | "express", 27 | "prisma", 28 | "realworld" 29 | ], 30 | "author": { 31 | "name": "Gerome Grignon", 32 | "email": "gerome.grignon.lp2@gmail.com" 33 | }, 34 | "license": "MIT", 35 | "dependencies": { 36 | "@prisma/client": "^3.4.2", 37 | "bcryptjs": "^2.4.3", 38 | "body-parser": "^1.19.0", 39 | "cors": "^2.8.5", 40 | "express": "^4.17.1", 41 | "express-jwt": "^6.1.0", 42 | "jsonwebtoken": "^8.5.1", 43 | "slugify": "^1.6.2" 44 | }, 45 | "devDependencies": { 46 | "@types/bcryptjs": "^2.4.2", 47 | "@types/cors": "^2.8.12", 48 | "@types/cron": "^1.7.3", 49 | "@types/express": "^4.17.13", 50 | "@types/express-rate-limit": "^5.1.3", 51 | "@types/jest": "^27.0.2", 52 | "@types/jsonwebtoken": "^8.5.5", 53 | "@types/node": "^15.14.9", 54 | "@typescript-eslint/eslint-plugin": "^4.33.0", 55 | "@typescript-eslint/parser": "^4.33.0", 56 | "eslint": "^7.32.0", 57 | "eslint-config-airbnb-base": "^15.0.0", 58 | "eslint-config-prettier": "^8.3.0", 59 | "eslint-plugin-import": "^2.25.3", 60 | "husky": "^7.0.4", 61 | "jest": "^27.3.1", 62 | "jest-mock-extended": "^2.0.4", 63 | "lint-staged": "^12.0.2", 64 | "prettier": "2.4.1", 65 | "prisma": "^3.4.2", 66 | "ts-jest": "^27.0.7", 67 | "ts-node-dev": "^1.1.8", 68 | "typescript": "^4.4.4" 69 | }, 70 | "lint-staged": { 71 | "*.ts": [ 72 | "npm run prisma:format", 73 | "npm run lint:fix", 74 | "npm run prettier:write", 75 | "git add" 76 | ] 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /prisma/migrations/20210924222830_initial/migration.sql: -------------------------------------------------------------------------------- 1 | -- CreateTable 2 | CREATE TABLE "Article" ( 3 | "id" SERIAL NOT NULL, 4 | "slug" TEXT NOT NULL, 5 | "title" TEXT NOT NULL, 6 | "description" TEXT NOT NULL, 7 | "body" TEXT NOT NULL, 8 | "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, 9 | "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, 10 | "authorId" INTEGER NOT NULL, 11 | 12 | PRIMARY KEY ("id") 13 | ); 14 | 15 | -- CreateTable 16 | CREATE TABLE "ArticleTags" ( 17 | "articleId" INTEGER NOT NULL, 18 | "tagId" INTEGER NOT NULL, 19 | 20 | PRIMARY KEY ("articleId","tagId") 21 | ); 22 | 23 | -- CreateTable 24 | CREATE TABLE "Comment" ( 25 | "id" SERIAL NOT NULL, 26 | "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, 27 | "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, 28 | "body" TEXT NOT NULL, 29 | "articleId" INTEGER NOT NULL, 30 | "authorId" INTEGER NOT NULL, 31 | 32 | PRIMARY KEY ("id") 33 | ); 34 | 35 | -- CreateTable 36 | CREATE TABLE "Tag" ( 37 | "id" SERIAL NOT NULL, 38 | "name" TEXT NOT NULL, 39 | 40 | PRIMARY KEY ("id") 41 | ); 42 | 43 | -- CreateTable 44 | CREATE TABLE "User" ( 45 | "id" SERIAL NOT NULL, 46 | "email" TEXT NOT NULL, 47 | "username" TEXT NOT NULL, 48 | "password" TEXT NOT NULL, 49 | "image" TEXT DEFAULT E'https://realworld-temp-api.herokuapp.com/images/smiley-cyrus.jpeg', 50 | "bio" TEXT, 51 | 52 | PRIMARY KEY ("id") 53 | ); 54 | 55 | -- CreateTable 56 | CREATE TABLE "_UserFavorites" ( 57 | "A" INTEGER NOT NULL, 58 | "B" INTEGER NOT NULL 59 | ); 60 | 61 | -- CreateTable 62 | CREATE TABLE "_UserFollows" ( 63 | "A" INTEGER NOT NULL, 64 | "B" INTEGER NOT NULL 65 | ); 66 | 67 | -- CreateIndex 68 | CREATE UNIQUE INDEX "Article.slug_unique" ON "Article"("slug"); 69 | 70 | -- CreateIndex 71 | CREATE UNIQUE INDEX "User.email_unique" ON "User"("email"); 72 | 73 | -- CreateIndex 74 | CREATE UNIQUE INDEX "User.username_unique" ON "User"("username"); 75 | 76 | -- CreateIndex 77 | CREATE UNIQUE INDEX "_UserFavorites_AB_unique" ON "_UserFavorites"("A", "B"); 78 | 79 | -- CreateIndex 80 | CREATE INDEX "_UserFavorites_B_index" ON "_UserFavorites"("B"); 81 | 82 | -- CreateIndex 83 | CREATE UNIQUE INDEX "_UserFollows_AB_unique" ON "_UserFollows"("A", "B"); 84 | 85 | -- CreateIndex 86 | CREATE INDEX "_UserFollows_B_index" ON "_UserFollows"("B"); 87 | 88 | -- AddForeignKey 89 | ALTER TABLE "Article" ADD FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; 90 | 91 | -- AddForeignKey 92 | ALTER TABLE "ArticleTags" ADD FOREIGN KEY ("articleId") REFERENCES "Article"("id") ON DELETE CASCADE ON UPDATE CASCADE; 93 | 94 | -- AddForeignKey 95 | ALTER TABLE "ArticleTags" ADD FOREIGN KEY ("tagId") REFERENCES "Tag"("id") ON DELETE CASCADE ON UPDATE CASCADE; 96 | 97 | -- AddForeignKey 98 | ALTER TABLE "Comment" ADD FOREIGN KEY ("articleId") REFERENCES "Article"("id") ON DELETE CASCADE ON UPDATE CASCADE; 99 | 100 | -- AddForeignKey 101 | ALTER TABLE "Comment" ADD FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; 102 | 103 | -- AddForeignKey 104 | ALTER TABLE "_UserFavorites" ADD FOREIGN KEY ("A") REFERENCES "Article"("id") ON DELETE CASCADE ON UPDATE CASCADE; 105 | 106 | -- AddForeignKey 107 | ALTER TABLE "_UserFavorites" ADD FOREIGN KEY ("B") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; 108 | 109 | -- AddForeignKey 110 | ALTER TABLE "_UserFollows" ADD FOREIGN KEY ("A") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; 111 | 112 | -- AddForeignKey 113 | ALTER TABLE "_UserFollows" ADD FOREIGN KEY ("B") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; 114 | -------------------------------------------------------------------------------- /tests/services/article.service.test.ts: -------------------------------------------------------------------------------- 1 | import prismaMock from '../prisma-mock'; 2 | import { favoriteArticle, unfavoriteArticle } from '../../src/services/article.service'; 3 | 4 | describe('ArticleService', () => { 5 | describe('favoriteArticle', () => { 6 | test('should return the favorited article', async () => { 7 | // Given 8 | const slug = 'How-to-train-your-dragon'; 9 | const username = 'RealWorld'; 10 | 11 | const mockedUserResponse = { 12 | id: 123, 13 | username: 'RealWorld', 14 | email: 'realworld@me', 15 | password: '1234', 16 | bio: null, 17 | image: null, 18 | token: '', 19 | }; 20 | 21 | const mockedArticleResponse = { 22 | id: 123, 23 | slug: 'How-to-train-your-dragon', 24 | title: 'How to train your dragon', 25 | description: '', 26 | body: '', 27 | createdAt: new Date(), 28 | updatedAt: new Date(), 29 | authorId: 456, 30 | tagList: [], 31 | favoritedBy: [ 32 | { 33 | username: 'Gerome', 34 | }, 35 | ], 36 | author: { 37 | id: 456, 38 | username: 'RealWorld', 39 | bio: null, 40 | image: null, 41 | followedBy: [], 42 | }, 43 | }; 44 | 45 | // When 46 | prismaMock.user.findUnique.mockResolvedValue(mockedUserResponse); 47 | prismaMock.article.update.mockResolvedValue(mockedArticleResponse); 48 | 49 | // Then 50 | await expect(favoriteArticle(slug, username)).resolves.toHaveProperty('favoritesCount'); 51 | }); 52 | 53 | test('should throw an error if no user is found', async () => { 54 | // Given 55 | const slug = 'how-to-train-your-dragon'; 56 | const username = 'RealWorld'; 57 | 58 | // When 59 | prismaMock.user.findUnique.mockResolvedValue(null); 60 | 61 | // Then 62 | await expect(favoriteArticle(slug, username)).rejects.toThrowError(); 63 | }); 64 | }); 65 | describe('unfavoriteArticle', () => { 66 | test('should return the unfavorited article', async () => { 67 | // Given 68 | const slug = 'How-to-train-your-dragon'; 69 | const username = 'RealWorld'; 70 | 71 | const mockedUserResponse = { 72 | id: 123, 73 | username: 'RealWorld', 74 | email: 'realworld@me', 75 | password: '1234', 76 | bio: null, 77 | image: null, 78 | token: '', 79 | }; 80 | 81 | const mockedArticleResponse = { 82 | id: 123, 83 | slug: 'How-to-train-your-dragon', 84 | title: 'How to train your dragon', 85 | description: '', 86 | body: '', 87 | createdAt: new Date(), 88 | updatedAt: new Date(), 89 | authorId: 456, 90 | tagList: [], 91 | favoritedBy: [], 92 | author: { 93 | id: 456, 94 | username: 'RealWorld', 95 | bio: null, 96 | image: null, 97 | followedBy: [], 98 | }, 99 | }; 100 | 101 | // When 102 | prismaMock.user.findUnique.mockResolvedValue(mockedUserResponse); 103 | prismaMock.article.update.mockResolvedValue(mockedArticleResponse); 104 | 105 | // Then 106 | await expect(unfavoriteArticle(slug, username)).resolves.toHaveProperty('favoritesCount'); 107 | }); 108 | 109 | test('should throw an error if no user is found', async () => { 110 | // Given 111 | const slug = 'how-to-train-your-dragon'; 112 | const username = 'RealWorld'; 113 | 114 | // When 115 | prismaMock.user.findUnique.mockResolvedValue(null); 116 | 117 | // Then 118 | await expect(unfavoriteArticle(slug, username)).rejects.toThrowError(); 119 | }); 120 | }); 121 | }); 122 | -------------------------------------------------------------------------------- /tests/services/profile.service.test.ts: -------------------------------------------------------------------------------- 1 | import prismaMock from '../prisma-mock'; 2 | import { followUser, getProfile, unfollowUser } from '../../src/services/profile.service'; 3 | 4 | describe('ProfileService', () => { 5 | describe('getProfile', () => { 6 | test('should return a following property', async () => { 7 | // Given 8 | const profileUsername = 'RealWorld'; 9 | const username = 'Gerome'; 10 | 11 | const mockedResponse = { 12 | id: 123, 13 | username: 'RealWorld', 14 | email: 'realworld@me', 15 | password: '1234', 16 | bio: null, 17 | image: null, 18 | token: '', 19 | followedBy: [], 20 | }; 21 | 22 | // When 23 | prismaMock.user.findUnique.mockResolvedValue(mockedResponse); 24 | 25 | // Then 26 | await expect(getProfile(profileUsername, username)).resolves.toHaveProperty('following'); 27 | }); 28 | 29 | test('should throw an error if no user is found', async () => { 30 | // Given 31 | const profileUsername = 'RealWorld'; 32 | const username = 'Gerome'; 33 | 34 | // When 35 | prismaMock.user.findUnique.mockResolvedValue(null); 36 | 37 | // Then 38 | await expect(getProfile(profileUsername, username)).rejects.toThrowError(); 39 | }); 40 | }); 41 | 42 | describe('followUser', () => { 43 | test('shoud return a following property', async () => { 44 | // Given 45 | const usernamePayload = 'AnotherUser'; 46 | const usernameAuth = 'RealWorld'; 47 | 48 | const mockedAuthUser = { 49 | id: 123, 50 | username: 'RealWorld', 51 | email: 'realworld@me', 52 | password: '1234', 53 | bio: null, 54 | image: null, 55 | token: '', 56 | followedBy: [], 57 | }; 58 | 59 | const mockedResponse = { 60 | id: 123, 61 | username: 'AnotherUser', 62 | email: 'another@me', 63 | password: '1234', 64 | bio: null, 65 | image: null, 66 | token: '', 67 | followedBy: [], 68 | }; 69 | 70 | // When 71 | prismaMock.user.findUnique.mockResolvedValue(mockedAuthUser); 72 | prismaMock.user.update.mockResolvedValue(mockedResponse); 73 | 74 | // Then 75 | await expect(followUser(usernamePayload, usernameAuth)).resolves.toHaveProperty('following'); 76 | }); 77 | 78 | test('shoud throw an error if no user is found', async () => { 79 | // Given 80 | const usernamePayload = 'AnotherUser'; 81 | const usernameAuth = 'RealWorld'; 82 | 83 | // When 84 | prismaMock.user.findUnique.mockResolvedValue(null); 85 | 86 | // Then 87 | await expect(followUser(usernamePayload, usernameAuth)).rejects.toThrowError(); 88 | }); 89 | }); 90 | 91 | describe('unfollowUser', () => { 92 | test('shoud return a following property', async () => { 93 | // Given 94 | const usernamePayload = 'AnotherUser'; 95 | const usernameAuth = 'RealWorld'; 96 | 97 | const mockedAuthUser = { 98 | id: 123, 99 | username: 'RealWorld', 100 | email: 'realworld@me', 101 | password: '1234', 102 | bio: null, 103 | image: null, 104 | token: '', 105 | followedBy: [], 106 | }; 107 | 108 | const mockedResponse = { 109 | id: 123, 110 | username: 'AnotherUser', 111 | email: 'another@me', 112 | password: '1234', 113 | bio: null, 114 | image: null, 115 | token: '', 116 | followedBy: [], 117 | }; 118 | 119 | // When 120 | prismaMock.user.findUnique.mockResolvedValue(mockedAuthUser); 121 | prismaMock.user.update.mockResolvedValue(mockedResponse); 122 | 123 | // Then 124 | await expect(unfollowUser(usernamePayload, usernameAuth)).resolves.toHaveProperty( 125 | 'following', 126 | ); 127 | }); 128 | 129 | test('shoud throw an error if no user is found', async () => { 130 | // Given 131 | const usernamePayload = 'AnotherUser'; 132 | const usernameAuth = 'RealWorld'; 133 | 134 | // When 135 | prismaMock.user.findUnique.mockResolvedValue(null); 136 | 137 | // Then 138 | await expect(unfollowUser(usernamePayload, usernameAuth)).rejects.toThrowError(); 139 | }); 140 | }); 141 | }); 142 | -------------------------------------------------------------------------------- /src/services/auth.service.ts: -------------------------------------------------------------------------------- 1 | import bcrypt from 'bcryptjs'; 2 | import prisma from '../../prisma/prisma-client'; 3 | import HttpException from '../models/http-exception.model'; 4 | import { 5 | UserCreatePayload, 6 | UserLoginPayload, 7 | UserResponse, 8 | UserUpdatePayload, 9 | } from '../models/user.model'; 10 | import userMapper from '../mappers/user.mapper'; 11 | import userSelector from '../selectors/user.selector'; 12 | 13 | const checkUserUniqueness = async (email: string, username: string): Promise => { 14 | const existingUserByEmail = await prisma.user.findUnique({ 15 | where: { 16 | email, 17 | }, 18 | select: { 19 | id: true, 20 | }, 21 | }); 22 | 23 | const existingUserByUsername = await prisma.user.findUnique({ 24 | where: { 25 | username, 26 | }, 27 | select: { 28 | id: true, 29 | }, 30 | }); 31 | 32 | if (existingUserByEmail || existingUserByUsername) { 33 | throw new HttpException(422, { 34 | errors: { 35 | ...(existingUserByEmail ? { email: ['has already been taken'] } : {}), 36 | ...(existingUserByUsername ? { username: ['has already been taken'] } : {}), 37 | }, 38 | }); 39 | } 40 | }; 41 | 42 | export const createUser = async (input: UserCreatePayload): Promise => { 43 | const email = input.email.trim(); 44 | const username = input.username.trim(); 45 | const password = input.password.trim(); 46 | 47 | if (!email) { 48 | throw new HttpException(422, { errors: { email: ["can't be blank"] } }); 49 | } 50 | 51 | if (!username) { 52 | throw new HttpException(422, { errors: { username: ["can't be blank"] } }); 53 | } 54 | 55 | if (!password) { 56 | throw new HttpException(422, { errors: { password: ["can't be blank"] } }); 57 | } 58 | 59 | await checkUserUniqueness(email, username); 60 | 61 | const hashedPassword = await bcrypt.hash(password, 10); 62 | 63 | const user = await prisma.user.create({ 64 | data: { 65 | username, 66 | email, 67 | password: hashedPassword, 68 | }, 69 | select: userSelector, 70 | }); 71 | 72 | return userMapper(user); 73 | }; 74 | 75 | export const login = async (userPayload: UserLoginPayload): Promise => { 76 | const email = userPayload.email.trim(); 77 | const password = userPayload.password.trim(); 78 | 79 | if (!email) { 80 | throw new HttpException(422, { errors: { email: ["can't be blank"] } }); 81 | } 82 | 83 | if (!password) { 84 | throw new HttpException(422, { errors: { password: ["can't be blank"] } }); 85 | } 86 | 87 | const user = await prisma.user.findUnique({ 88 | where: { 89 | email, 90 | }, 91 | select: { 92 | email: true, 93 | username: true, 94 | password: true, 95 | bio: true, 96 | image: true, 97 | }, 98 | }); 99 | 100 | if (user) { 101 | const match = await bcrypt.compare(password, user.password); 102 | 103 | if (match) { 104 | return userMapper(user); 105 | } 106 | } 107 | 108 | throw new HttpException(403, { 109 | errors: { 110 | 'email or password': ['is invalid'], 111 | }, 112 | }); 113 | }; 114 | 115 | export const getCurrentUser = async (username: string): Promise => { 116 | const user = await prisma.user.findUnique({ 117 | where: { 118 | username, 119 | }, 120 | select: userSelector, 121 | }); 122 | 123 | if (!user) { 124 | throw new HttpException(404, {}); 125 | } 126 | 127 | return userMapper(user); 128 | }; 129 | 130 | export const updateUser = async ( 131 | userPayload: UserUpdatePayload, 132 | loggedInUsername: string, 133 | ): Promise => { 134 | const { email, username, password, image, bio } = userPayload; 135 | const user = await prisma.user.update({ 136 | where: { 137 | username: loggedInUsername, 138 | }, 139 | data: { 140 | ...(email ? { email } : {}), 141 | ...(username ? { username } : {}), 142 | ...(password ? { password } : {}), 143 | ...(image ? { image } : {}), 144 | ...(bio ? { bio } : {}), 145 | }, 146 | select: userSelector, 147 | }); 148 | 149 | return userMapper(user); 150 | }; 151 | 152 | export const findUserIdByUsername = async (username: string): Promise => { 153 | const user = await prisma.user.findUnique({ 154 | where: { 155 | username, 156 | }, 157 | select: { 158 | id: true, 159 | }, 160 | }); 161 | 162 | if (!user) { 163 | throw new HttpException(404, {}); 164 | } 165 | 166 | return user.id; 167 | }; 168 | -------------------------------------------------------------------------------- /src/controllers/article.controller.ts: -------------------------------------------------------------------------------- 1 | import { NextFunction, Request, Response, Router } from 'express'; 2 | import auth from '../utils/auth'; 3 | import { 4 | createArticle, 5 | deleteArticle, 6 | favoriteArticle, 7 | getArticle, 8 | getArticles, 9 | getFeed, 10 | unfavoriteArticle, 11 | updateArticle, 12 | } from '../services/article.service'; 13 | 14 | const router = Router(); 15 | 16 | /** 17 | * Get paginated articles 18 | * @auth optional 19 | * @route {GET} /articles 20 | * @queryparam offset number of articles dismissed from the first one 21 | * @queryparam limit number of articles returned 22 | * @queryparam tag 23 | * @queryparam author 24 | * @queryparam favorited 25 | * @returns articles: list of articles 26 | */ 27 | router.get('/articles', auth.optional, async (req: Request, res: Response, next: NextFunction) => { 28 | try { 29 | const articles = await getArticles(req.query, req.user?.username); 30 | res.json(articles); 31 | } catch (error) { 32 | next(error); 33 | } 34 | }); 35 | 36 | /** 37 | * Get paginated feed articles 38 | * @auth required 39 | * @route {GET} /articles/feed 40 | * @returns articles list of articles 41 | */ 42 | router.get( 43 | '/articles/feed', 44 | auth.required, 45 | async (req: Request, res: Response, next: NextFunction) => { 46 | try { 47 | const articles = await getFeed( 48 | Number(req.query.offset), 49 | Number(req.query.limit), 50 | req.user!.username, 51 | ); 52 | res.json(articles); 53 | } catch (error) { 54 | next(error); 55 | } 56 | }, 57 | ); 58 | 59 | /** 60 | * Create article 61 | * @route {POST} /articles 62 | * @bodyparam title 63 | * @bodyparam description 64 | * @bodyparam body 65 | * @bodyparam tagList list of tags 66 | * @returns article created article 67 | */ 68 | router.post('/articles', auth.required, async (req: Request, res: Response, next: NextFunction) => { 69 | try { 70 | const article = await createArticle(req.body.article, req.user!.username); 71 | res.json({ article }); 72 | } catch (error) { 73 | next(error); 74 | } 75 | }); 76 | 77 | /** 78 | * Get unique article 79 | * @auth optional 80 | * @route {GET} /article/:slug 81 | * @param slug slug of the article (based on the title) 82 | * @returns article 83 | */ 84 | router.get( 85 | '/articles/:slug', 86 | auth.optional, 87 | async (req: Request, res: Response, next: NextFunction) => { 88 | try { 89 | const article = await getArticle(req.params.slug, req.user?.username as string | undefined); 90 | res.json({ article }); 91 | } catch (error) { 92 | next(error); 93 | } 94 | }, 95 | ); 96 | 97 | /** 98 | * Update article 99 | * @auth required 100 | * @route {PUT} /articles/:slug 101 | * @param slug slug of the article (based on the title) 102 | * @bodyparam title new title 103 | * @bodyparam description new description 104 | * @bodyparam body new content 105 | * @returns article updated article 106 | */ 107 | router.put( 108 | '/articles/:slug', 109 | auth.required, 110 | async (req: Request, res: Response, next: NextFunction) => { 111 | try { 112 | const article = await updateArticle(req.body.article, req.params.slug, req.user!.username); 113 | res.json({ article }); 114 | } catch (error) { 115 | next(error); 116 | } 117 | }, 118 | ); 119 | 120 | /** 121 | * Delete article 122 | * @auth required 123 | * @route {DELETE} /article/:id 124 | * @param slug slug of the article 125 | */ 126 | router.delete( 127 | '/articles/:slug', 128 | auth.required, 129 | async (req: Request, res: Response, next: NextFunction) => { 130 | try { 131 | await deleteArticle(req.params.slug, req.user!.username); 132 | res.sendStatus(204); 133 | } catch (error) { 134 | next(error); 135 | } 136 | }, 137 | ); 138 | 139 | /** 140 | * Favorite article 141 | * @auth required 142 | * @route {POST} /articles/:slug/favorite 143 | * @param slug slug of the article (based on the title) 144 | * @returns article favorited article 145 | */ 146 | router.post( 147 | '/articles/:slug/favorite', 148 | auth.required, 149 | async (req: Request, res: Response, next: NextFunction) => { 150 | try { 151 | const article = await favoriteArticle(req.params.slug, req.user!.username); 152 | res.json({ article }); 153 | } catch (error) { 154 | next(error); 155 | } 156 | }, 157 | ); 158 | 159 | /** 160 | * Unfavorite article 161 | * @auth required 162 | * @route {DELETE} /articles/:slug/favorite 163 | * @param slug slug of the article (based on the title) 164 | * @returns article unfavorited article 165 | */ 166 | router.delete( 167 | '/articles/:slug/favorite', 168 | auth.required, 169 | async (req: Request, res: Response, next: NextFunction) => { 170 | try { 171 | const article = await unfavoriteArticle(req.params.slug, req.user!.username); 172 | res.json({ article }); 173 | } catch (error) { 174 | next(error); 175 | } 176 | }, 177 | ); 178 | 179 | export default router; 180 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | - Demonstrating empathy and kindness toward other people 21 | - Being respectful of differing opinions, viewpoints, and experiences 22 | - Giving and gracefully accepting constructive feedback 23 | - Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | - Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | - The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | - Trolling, insulting or derogatory comments, and personal or political attacks 33 | - Public or private harassment 34 | - Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | - Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | hello@thinkster.io. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 4 | 5 | /* Basic Options */ 6 | // "incremental": true, /* Enable incremental compilation */ 7 | "target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */, 8 | "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, 9 | "lib": ["es2015"] /* Specify library files to be included in the compilation. */, 10 | // "allowJs": true, /* Allow javascript files to be compiled. */ 11 | // "checkJs": true, /* Report errors in .js files. */ 12 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 13 | // "declaration": true, /* Generates corresponding '.d.ts' file. */ 14 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 15 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 16 | // "outFile": "./", /* Concatenate and emit output to single file. */ 17 | "outDir": "dist" /* Redirect output structure to the directory. */, 18 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 19 | // "composite": true, /* Enable project compilation */ 20 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 21 | // "removeComments": true, /* Do not emit comments to output. */ 22 | // "noEmit": true, /* Do not emit outputs. */ 23 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 24 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 25 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 26 | 27 | /* Strict Type-Checking Options */ 28 | "strict": true /* Enable all strict type-checking options. */, 29 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 30 | // "strictNullChecks": true, /* Enable strict null checks. */ 31 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 32 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 33 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 34 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 35 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 36 | 37 | /* Additional Checks */ 38 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 39 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 40 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 41 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 42 | 43 | /* Module Resolution Options */ 44 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 45 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 46 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 47 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 48 | // "typeRoots": [], /* List of folders to include type definitions from. */ 49 | // "types": [], /* Type declaration files to be included in compilation. */ 50 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 51 | "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, 52 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 53 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 54 | 55 | /* Source Map Options */ 56 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 57 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 58 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 59 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 60 | 61 | /* Experimental Options */ 62 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 63 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 64 | 65 | /* Advanced Options */ 66 | "resolveJsonModule": true, 67 | "skipLibCheck": true /* Skip type checking of declaration files. */, 68 | "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ 69 | }, 70 | "exclude": ["tests"] 71 | } 72 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to RealWorld 2 | 3 | We would love for you to contribute to RealWorld and help make it even better than it is 4 | today! As a contributor, here are the guidelines we would like you to follow: 5 | 6 | - [Code of Conduct](#coc) 7 | - [Question or Problem?](#question) 8 | - [Issues and Bugs](#issue) 9 | - [Feature Requests](#feature) 10 | - [Submission Guidelines](#submit) 11 | - [Coding Rules](#rules) 12 | - [Commit Message Guidelines](#commit) 13 | 14 | ## Code of Conduct 15 | 16 | Help us keep RealWorld open and inclusive. Please read and follow our [Code of Conduct][coc]. 17 | 18 | ## Got a Question or Problem? 19 | 20 | Do not open issues for general support questions as we want to keep GitHub issues for bug reports and feature requests. 21 | For open discussions, we encourage you to use the [Github Discussions][github-discussions] channels of the RealWorld repository. 22 | 23 | ## Found a Bug? 24 | 25 | If you find a bug in the project, you can help us by 26 | [submitting an issue][github-issue] to our [GitHub Repository][github]. Even better, you can 27 | [submit a Pull Request](#submit-pr) with a fix. 28 | 29 | ## Missing a Feature? 30 | 31 | This repository follows the RealWorld [specs][github-spec]. 32 | Please open feature requests on the RealWorld [repository][github-feature]. 33 | 34 | ## Submission Guidelines 35 | 36 | ### Submitting an Issue 37 | 38 | Before you submit an issue, please search the issue tracker, maybe an issue for your problem already exists and the discussion might inform you of workarounds readily available. 39 | 40 | You can file new issues by selecting from our [new issue templates][github-choose] and filling out the issue template. 41 | 42 | ### Submitting a Pull Request (PR) 43 | 44 | Before you submit your Pull Request (PR) consider the following guidelines: 45 | 46 | 1. Search [GitHub](https://github.com/gothinkster/node-express-prisma-v2-official-app/pulls) for an open or closed PR 47 | that relates to your submission. You don't want to duplicate effort. 48 | 1. Be sure that an issue describes the problem you're fixing, or documents the design for the feature you'd like to add. 49 | Discussing the design up front helps to ensure that we're ready to accept your work. 50 | 1. Fork the gothinkster/realworld repo. 51 | 1. Make your changes in a new git branch: 52 | 53 | ```bash 54 | git checkout -b my-fix-branch main 55 | ``` 56 | 57 | 1. Create your patch. 58 | 59 | 1. Commit your changes using a descriptive commit message that follows our 60 | [commit message conventions](#commit). 61 | 62 | 1. Push your branch to GitHub: 63 | 64 | ```bash 65 | git push origin my-fix-branch 66 | ``` 67 | 68 | 1. In GitHub, send a pull request to `node-express-prisma-v2-official-app:main`. 69 | 70 | - If we suggest changes then: 71 | 72 | - Make the required updates. 73 | - Rebase your branch and force push to your GitHub repository (this will update your Pull Request): 74 | 75 | ```bash 76 | git rebase main -i 77 | git push -f 78 | ``` 79 | 80 | That's it! Thank you for your contribution! 81 | 82 | #### After your pull request is merged 83 | 84 | After your pull request is merged, you can safely delete your branch and pull the changes 85 | from the main (upstream) repository: 86 | 87 | - Delete the remote branch on GitHub either through the GitHub web UI or your local shell as follows: 88 | 89 | ```bash 90 | git push origin --delete my-fix-branch 91 | ``` 92 | 93 | - Check out the main branch: 94 | 95 | ```bash 96 | git checkout main -f 97 | ``` 98 | 99 | - Delete the local branch: 100 | 101 | ```bash 102 | git branch -D my-fix-branch 103 | ``` 104 | 105 | - Update your main with the latest upstream version: 106 | 107 | ```bash 108 | git pull --ff upstream main 109 | ``` 110 | 111 | ## Commit Message Guidelines 112 | 113 | > These guidelines have been added to the project starting from 114 | 115 | We have very precise rules over how our git commit messages can be formatted. This leads to **more 116 | readable messages** that are easy to follow when looking through the **project history**. 117 | 118 | ### Commit Message Format 119 | 120 | Each commit message consists of a **header**, a **body** and a **footer**. The header has a special 121 | format that includes a **type**, a **scope** and a **subject**: 122 | 123 | ``` 124 | (): 125 | 126 | 127 | 128 |