mirror of
https://github.com/hknsh/project-knedita.git
synced 2024-11-28 17:41:15 +00:00
Changed to Typescript. Added Create Post route and model.
This commit is contained in:
parent
e214f59fca
commit
4b301eb985
34 changed files with 1525 additions and 195 deletions
2
.gitignore
vendored
2
.gitignore
vendored
|
@ -4,3 +4,5 @@ node_modules
|
||||||
prisma/*.db
|
prisma/*.db
|
||||||
.DS_Store
|
.DS_Store
|
||||||
prisma/migrations/dev
|
prisma/migrations/dev
|
||||||
|
client
|
||||||
|
dist
|
14
Dockerfile
14
Dockerfile
|
@ -6,10 +6,24 @@ WORKDIR /app
|
||||||
COPY package*.json ./
|
COPY package*.json ./
|
||||||
COPY prisma ./prisma/
|
COPY prisma ./prisma/
|
||||||
|
|
||||||
|
RUN npm install pm2 -g
|
||||||
RUN npm install
|
RUN npm install
|
||||||
|
|
||||||
COPY . .
|
COPY . .
|
||||||
|
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# Stage 2
|
||||||
|
FROM node:16
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY --from=builder /app/package*.json ./
|
||||||
|
COPY --from=builder /app/prisma ./prisma/
|
||||||
|
COPY --from=builder /app/dist ./dist/
|
||||||
|
|
||||||
|
RUN npm ci
|
||||||
|
|
||||||
EXPOSE 8080
|
EXPOSE 8080
|
||||||
|
|
||||||
CMD ["npm", "run", "prod:start"]
|
CMD ["npm", "run", "prod:start"]
|
5
jest.config.js
Normal file
5
jest.config.js
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
/** @type {import('ts-jest').JestConfigWithTsJest} */
|
||||||
|
module.exports = {
|
||||||
|
preset: 'ts-jest',
|
||||||
|
testEnvironment: 'node'
|
||||||
|
}
|
1166
package-lock.json
generated
1166
package-lock.json
generated
File diff suppressed because it is too large
Load diff
36
package.json
36
package.json
|
@ -2,10 +2,9 @@
|
||||||
"name": "social-media-app",
|
"name": "social-media-app",
|
||||||
"version": "0.0.1",
|
"version": "0.0.1",
|
||||||
"description": "A social media",
|
"description": "A social media",
|
||||||
"main": "src/server.js",
|
|
||||||
"type": "module",
|
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev:start": "nodemon src/server.js",
|
"build": "tsc --build",
|
||||||
|
"dev:start": "ts-node-dev --transpile-only --respawn src/server.ts",
|
||||||
"docker": "docker compose up -d",
|
"docker": "docker compose up -d",
|
||||||
"docker:build": "docker build -t api . && docker compose up -d",
|
"docker:build": "docker build -t api . && docker compose up -d",
|
||||||
"docker:db": "docker compose -f docker-compose.db.yml up -d",
|
"docker:db": "docker compose -f docker-compose.db.yml up -d",
|
||||||
|
@ -16,23 +15,42 @@
|
||||||
"prisma:generate": "npx prisma generate",
|
"prisma:generate": "npx prisma generate",
|
||||||
"prisma:seed": "prisma db seed",
|
"prisma:seed": "prisma db seed",
|
||||||
"prisma:studio": "npx prisma studio",
|
"prisma:studio": "npx prisma studio",
|
||||||
"prod:start": "pm2-runtime start src/server.js",
|
"prod:start": "nodemon dist/src/server.js",
|
||||||
"test": "node --experimental-vm-modules --no-warnings node_modules/jest/bin/jest.js"
|
"test": "jest"
|
||||||
},
|
},
|
||||||
"standard": {
|
"aliases": {
|
||||||
|
"@services": "./src/services",
|
||||||
|
"@db": "./prisma"
|
||||||
|
},
|
||||||
|
"ts-standard": {
|
||||||
|
"project": "tsconfig.json",
|
||||||
"ignore": [
|
"ignore": [
|
||||||
"/src/tests/*.spec.js"
|
"prisma/*",
|
||||||
|
"dist"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"author": "Cookie",
|
"author": "Cookie",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@types/bcrypt": "^5.0.0",
|
||||||
|
"@types/compression": "^1.7.2",
|
||||||
|
"@types/dotenv": "^8.2.0",
|
||||||
|
"@types/express": "^4.17.17",
|
||||||
|
"@types/jest": "^29.5.2",
|
||||||
|
"@types/jsonwebtoken": "^9.0.2",
|
||||||
|
"@types/node": "^20.3.1",
|
||||||
|
"@types/supertest": "^2.0.12",
|
||||||
|
"@types/validator": "^13.7.17",
|
||||||
|
"@typescript-eslint/eslint-plugin": "^5.60.0",
|
||||||
"jest": "^29.5.0",
|
"jest": "^29.5.0",
|
||||||
"nodemon": "^2.0.22",
|
"nodemon": "^2.0.22",
|
||||||
"pm2": "^5.3.0",
|
"pm2": "^5.3.0",
|
||||||
"prisma": "^4.16.0",
|
"prisma": "^4.16.0",
|
||||||
"standard": "^17.1.0",
|
"supertest": "^6.3.3",
|
||||||
"supertest": "^6.3.3"
|
"ts-jest": "^29.1.0",
|
||||||
|
"ts-node-dev": "^2.0.0",
|
||||||
|
"ts-standard": "^12.0.2",
|
||||||
|
"typescript": "^5.1.3"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@prisma/client": "^4.16.0",
|
"@prisma/client": "^4.16.0",
|
||||||
|
|
|
@ -1,5 +1,7 @@
|
||||||
import { PrismaClient } from '@prisma/client'
|
import { PrismaClient } from '@prisma/client'
|
||||||
|
|
||||||
|
// Cria uma instância do cliente Prisma
|
||||||
const prisma = new PrismaClient()
|
const prisma = new PrismaClient()
|
||||||
|
|
||||||
|
// Exporta o cliente Prisma para ser usado em outros módulos
|
||||||
export default prisma
|
export default prisma
|
|
@ -0,0 +1,13 @@
|
||||||
|
-- CreateTable
|
||||||
|
CREATE TABLE "Post" (
|
||||||
|
"id" TEXT NOT NULL,
|
||||||
|
"content" TEXT NOT NULL,
|
||||||
|
"authorId" TEXT NOT NULL,
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT "Post_pkey" PRIMARY KEY ("id")
|
||||||
|
);
|
||||||
|
|
||||||
|
-- AddForeignKey
|
||||||
|
ALTER TABLE "Post" ADD CONSTRAINT "Post_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
|
@ -16,5 +16,15 @@ model User {
|
||||||
username String @unique
|
username String @unique
|
||||||
email String @unique
|
email String @unique
|
||||||
password String
|
password String
|
||||||
|
posts Post[]
|
||||||
createdAt DateTime @default(now())
|
createdAt DateTime @default(now())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
model Post {
|
||||||
|
id String @id @default(uuid())
|
||||||
|
content String
|
||||||
|
authorId String
|
||||||
|
author User @relation(fields: [authorId], references: [id])
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @default(now())
|
||||||
|
}
|
10
src/@types/express.d.ts
vendored
Normal file
10
src/@types/express.d.ts
vendored
Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
import * as express from 'express'
|
||||||
|
import jwtPayload from '../interfaces/jwt'
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
namespace Express {
|
||||||
|
interface Request {
|
||||||
|
user: jwtPayload | undefined
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
|
@ -1,7 +1,7 @@
|
||||||
import 'dotenv/config'
|
import 'dotenv/config'
|
||||||
|
|
||||||
import express from 'express'
|
import express from 'express'
|
||||||
import router from './routes.js'
|
import router from './routes'
|
||||||
import compression from 'compression'
|
import compression from 'compression'
|
||||||
|
|
||||||
const app = express()
|
const app = express()
|
20
src/controllers/post/create-post.ts
Normal file
20
src/controllers/post/create-post.ts
Normal file
|
@ -0,0 +1,20 @@
|
||||||
|
import createPostService from '../../services/post/create-post'
|
||||||
|
import { Request, Response } from 'express'
|
||||||
|
|
||||||
|
async function createPostController (req: Request, res: Response): Promise<void> {
|
||||||
|
const { content } = req.body
|
||||||
|
const id: string = req.user?.id ?? ''
|
||||||
|
|
||||||
|
const result = await createPostService(content, id)
|
||||||
|
|
||||||
|
if (result instanceof Error) {
|
||||||
|
res.status(400).json({
|
||||||
|
error: result.message
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default createPostController
|
|
@ -1,17 +0,0 @@
|
||||||
import userAuthService from '../services/user-auth.js'
|
|
||||||
|
|
||||||
async function userAuthController (req, res) {
|
|
||||||
const { email, password } = req.body
|
|
||||||
|
|
||||||
const result = await userAuthService({ email, password })
|
|
||||||
|
|
||||||
if (result instanceof Error) {
|
|
||||||
return res.status(400).json({
|
|
||||||
error: result.message
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
res.json(result)
|
|
||||||
}
|
|
||||||
|
|
||||||
export default userAuthController
|
|
|
@ -1,15 +0,0 @@
|
||||||
import userInfoService from '../services/user-info.js'
|
|
||||||
|
|
||||||
async function userInfoController (req, res) {
|
|
||||||
const result = await userInfoService(req)
|
|
||||||
|
|
||||||
if (result instanceof Error) {
|
|
||||||
return res.status(400).json({
|
|
||||||
error: result.message
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
res.json(result)
|
|
||||||
}
|
|
||||||
|
|
||||||
export default userInfoController
|
|
|
@ -1,17 +0,0 @@
|
||||||
import userSignupService from '../services/user-signup.js'
|
|
||||||
|
|
||||||
async function userSignupController (req, res) {
|
|
||||||
const { username, email, password } = req.body
|
|
||||||
|
|
||||||
const result = await userSignupService({ username, email, password })
|
|
||||||
|
|
||||||
if (result instanceof Error) {
|
|
||||||
return res.status(400).json({
|
|
||||||
error: result.message
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return res.json(result)
|
|
||||||
}
|
|
||||||
|
|
||||||
export default userSignupController
|
|
19
src/controllers/user/user-auth.ts
Normal file
19
src/controllers/user/user-auth.ts
Normal file
|
@ -0,0 +1,19 @@
|
||||||
|
import userAuthService from '../../services/user/user-auth'
|
||||||
|
import type { Request, Response } from 'express'
|
||||||
|
|
||||||
|
async function userAuthController (req: Request, res: Response): Promise<void> {
|
||||||
|
const { email, password } = req.body
|
||||||
|
|
||||||
|
const result = await userAuthService(email, password)
|
||||||
|
|
||||||
|
if (result instanceof Error) {
|
||||||
|
res.status(400).json({
|
||||||
|
error: result.message
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default userAuthController
|
19
src/controllers/user/user-info.ts
Normal file
19
src/controllers/user/user-info.ts
Normal file
|
@ -0,0 +1,19 @@
|
||||||
|
import userInfoService from '../../services/user/user-info'
|
||||||
|
import type { Request, Response } from 'express'
|
||||||
|
|
||||||
|
async function userInfoController (req: Request, res: Response): Promise<void> {
|
||||||
|
const id = req.user?.id ?? ''
|
||||||
|
|
||||||
|
const result = await userInfoService(id)
|
||||||
|
|
||||||
|
if (result instanceof Error) {
|
||||||
|
res.status(400).json({
|
||||||
|
error: result.message
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default userInfoController
|
19
src/controllers/user/user-signup.ts
Normal file
19
src/controllers/user/user-signup.ts
Normal file
|
@ -0,0 +1,19 @@
|
||||||
|
import userSignupService from '../../services/user/user-signup'
|
||||||
|
import type { Request, Response } from 'express'
|
||||||
|
|
||||||
|
async function userSignupController (req: Request, res: Response): Promise<void> {
|
||||||
|
const { username, email, password } = req.body
|
||||||
|
|
||||||
|
const result = await userSignupService(username, email, password)
|
||||||
|
|
||||||
|
if (result instanceof Error) {
|
||||||
|
res.status(400).json({
|
||||||
|
error: result.message
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
export default userSignupController
|
7
src/interfaces/jwt.ts
Normal file
7
src/interfaces/jwt.ts
Normal file
|
@ -0,0 +1,7 @@
|
||||||
|
interface jwtPayload {
|
||||||
|
id: string
|
||||||
|
iat: number
|
||||||
|
exp: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export default jwtPayload
|
|
@ -1,38 +0,0 @@
|
||||||
import jsonwebtoken from 'jsonwebtoken'
|
|
||||||
import prisma from '../../prisma/client.js'
|
|
||||||
|
|
||||||
function ensureAuthenticated (req, res, next) {
|
|
||||||
if (!req.headers.authorization || req.headers.authorization.length === 0) {
|
|
||||||
return res.status(401).json({
|
|
||||||
error: 'Missing token'
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const token = req.headers.authorization.split(' ')[1]
|
|
||||||
|
|
||||||
jsonwebtoken.verify(token, process.env.JWT_ACCESS_SECRET, async (err, decoded) => {
|
|
||||||
if (err || !decoded) {
|
|
||||||
return res.status(401).json({
|
|
||||||
error: err.message
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
const user = await prisma.user.findFirst({
|
|
||||||
where: {
|
|
||||||
id: decoded.id
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
return res.status(401).json({
|
|
||||||
error: 'Invalid user'
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
req.user = decoded
|
|
||||||
|
|
||||||
return next()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
export default ensureAuthenticated
|
|
57
src/middlewares/ensure-authenticated.ts
Normal file
57
src/middlewares/ensure-authenticated.ts
Normal file
|
@ -0,0 +1,57 @@
|
||||||
|
import { verify } from 'jsonwebtoken'
|
||||||
|
import prisma from '../../prisma/client'
|
||||||
|
import { Response, Request, NextFunction } from 'express'
|
||||||
|
import jwtPayload from '../interfaces/jwt'
|
||||||
|
|
||||||
|
async function ensureAuthenticated (req: Request, res: Response, next: NextFunction): Promise<void> {
|
||||||
|
if (req.headers.authorization === undefined || req.headers.authorization.length === 0) {
|
||||||
|
res.status(401).json({
|
||||||
|
error: 'Missing token'
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = req.headers.authorization.split(' ')[1]
|
||||||
|
|
||||||
|
try {
|
||||||
|
const decoded = await new Promise<jwtPayload | undefined>((resolve, reject) => {
|
||||||
|
verify(token, process.env.JWT_ACCESS_SECRET ?? '', (error, decoded) => {
|
||||||
|
if (error != null) {
|
||||||
|
reject(error)
|
||||||
|
} else {
|
||||||
|
resolve(decoded as jwtPayload)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
if (decoded == null) {
|
||||||
|
res.status(401).json({
|
||||||
|
error: 'Invalid token'
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await prisma.user.findFirst({
|
||||||
|
where: {
|
||||||
|
id: decoded.id
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
if (user == null) {
|
||||||
|
res.status(401).json({
|
||||||
|
error: 'Invalid user'
|
||||||
|
})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
req.user = decoded
|
||||||
|
|
||||||
|
return next()
|
||||||
|
} catch (error) {
|
||||||
|
res.status(401).json({
|
||||||
|
error: (error as Error).message
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default ensureAuthenticated
|
|
@ -1,14 +0,0 @@
|
||||||
import { Router } from 'express'
|
|
||||||
|
|
||||||
import userSignupController from './controllers/user-signup.js'
|
|
||||||
import userAuthController from './controllers/user-auth.js'
|
|
||||||
import userInfoController from './controllers/user-info.js'
|
|
||||||
import ensureAuthenticated from './middlewares/ensure-authenticated.js'
|
|
||||||
|
|
||||||
const router = Router()
|
|
||||||
|
|
||||||
router.post('/user/create', userSignupController)
|
|
||||||
router.post('/user/auth', userAuthController)
|
|
||||||
router.get('/user/info', ensureAuthenticated, userInfoController)
|
|
||||||
|
|
||||||
export default router
|
|
22
src/routes.ts
Normal file
22
src/routes.ts
Normal file
|
@ -0,0 +1,22 @@
|
||||||
|
import { Router } from 'express'
|
||||||
|
|
||||||
|
// Controllers
|
||||||
|
import userSignupController from './controllers/user/user-signup'
|
||||||
|
import userAuthController from './controllers/user/user-auth'
|
||||||
|
import userInfoController from './controllers/user/user-info'
|
||||||
|
import createPostController from './controllers/post/create-post'
|
||||||
|
|
||||||
|
// Middlewares
|
||||||
|
import ensureAuthenticated from './middlewares/ensure-authenticated'
|
||||||
|
|
||||||
|
const router = Router()
|
||||||
|
|
||||||
|
// User related
|
||||||
|
router.post('/user/auth', userAuthController)
|
||||||
|
router.post('/user/create', userSignupController)
|
||||||
|
router.get('/user/info', ensureAuthenticated, userInfoController)
|
||||||
|
|
||||||
|
// Post related
|
||||||
|
router.post('/post/create', ensureAuthenticated, createPostController)
|
||||||
|
|
||||||
|
export default router
|
|
@ -1,5 +0,0 @@
|
||||||
import app from './app.js'
|
|
||||||
|
|
||||||
app.listen(process.env.SERVER_PORT, () => {
|
|
||||||
console.log(`Server is running @ ${process.env.SERVER_PORT}`)
|
|
||||||
})
|
|
5
src/server.ts
Normal file
5
src/server.ts
Normal file
|
@ -0,0 +1,5 @@
|
||||||
|
import app from './app'
|
||||||
|
|
||||||
|
app.listen(process.env.SERVER_PORT, () => {
|
||||||
|
console.log(`Server is running @ ${process.env.SERVER_PORT ?? ''}`)
|
||||||
|
})
|
20
src/services/post/create-post.ts
Normal file
20
src/services/post/create-post.ts
Normal file
|
@ -0,0 +1,20 @@
|
||||||
|
import prisma from '../../../prisma/client'
|
||||||
|
|
||||||
|
async function createPostService (content: string, authorId: string) {
|
||||||
|
const user = await prisma.user.findFirst({ where: { id: authorId } })
|
||||||
|
|
||||||
|
if (user == null) {
|
||||||
|
return new Error('This user doesn\'t exists')
|
||||||
|
}
|
||||||
|
|
||||||
|
const post = await prisma.post.create({
|
||||||
|
data: {
|
||||||
|
content,
|
||||||
|
authorId
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
return post
|
||||||
|
}
|
||||||
|
|
||||||
|
export default createPostService
|
|
@ -1,15 +1,15 @@
|
||||||
import * as bcrypt from 'bcrypt'
|
import * as bcrypt from 'bcrypt'
|
||||||
import jsonwebtoken from 'jsonwebtoken'
|
import jsonwebtoken from 'jsonwebtoken'
|
||||||
import prisma from '../../prisma/client.js'
|
import prisma from '../../../prisma/client'
|
||||||
|
|
||||||
async function userAuthService ({ email, password }) {
|
async function userAuthService (email: string, password: string): Promise<Object | Error> {
|
||||||
const user = await prisma.user.findFirst({
|
const user = await prisma.user.findFirst({
|
||||||
where: {
|
where: {
|
||||||
email
|
email
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
if (!user) {
|
if (user == null) {
|
||||||
return new Error('User does not exists')
|
return new Error('User does not exists')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -19,13 +19,13 @@ async function userAuthService ({ email, password }) {
|
||||||
|
|
||||||
const validPassword = await bcrypt.compare(password, user.password)
|
const validPassword = await bcrypt.compare(password, user.password)
|
||||||
|
|
||||||
if (validPassword === false) {
|
if (!validPassword) {
|
||||||
return new Error('Invalid email or password')
|
return new Error('Invalid email or password')
|
||||||
}
|
}
|
||||||
|
|
||||||
const { id } = user
|
const { id } = user
|
||||||
|
|
||||||
const bearer = jsonwebtoken.sign({ id }, process.env.JWT_ACCESS_SECRET, { expiresIn: '1d' })
|
const bearer = jsonwebtoken.sign({ id }, process.env.JWT_ACCESS_SECRET ?? '', { expiresIn: '1d' })
|
||||||
|
|
||||||
return {
|
return {
|
||||||
token: bearer
|
token: bearer
|
|
@ -1,11 +1,9 @@
|
||||||
import prisma from '../../prisma/client.js'
|
import prisma from '../../../prisma/client'
|
||||||
|
|
||||||
async function userInfoService (req) {
|
|
||||||
const userId = req.user.id
|
|
||||||
|
|
||||||
|
async function userInfoService (id: string): Promise<Object> {
|
||||||
const user = await prisma.user.findFirst({
|
const user = await prisma.user.findFirst({
|
||||||
where: {
|
where: {
|
||||||
id: userId
|
id
|
||||||
},
|
},
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
id: true,
|
||||||
|
@ -15,6 +13,10 @@ async function userInfoService (req) {
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
if (user === null) {
|
||||||
|
return new Error('User not found')
|
||||||
|
}
|
||||||
|
|
||||||
return user
|
return user
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,20 +1,25 @@
|
||||||
import * as bcrypt from 'bcrypt'
|
import * as bcrypt from 'bcrypt'
|
||||||
import prisma from '../../prisma/client.js'
|
import validator from 'validator'
|
||||||
|
import prisma from '../../../prisma/client'
|
||||||
|
|
||||||
async function userSignupService ({ username, email, password }) {
|
async function userSignupService (username: string, email: string, password: string): Promise<Object | Error> {
|
||||||
if (!username || !email || !password) {
|
if (username === undefined || email === undefined || password === undefined) {
|
||||||
return new Error('Missing fields')
|
return new Error('Missing fields')
|
||||||
}
|
}
|
||||||
|
|
||||||
if (/^[a-zA-Z0-9_]{5,15}$/.test(username) === false) {
|
if (!/^[a-zA-Z0-9_]{5,15}$/.test(username)) {
|
||||||
return new Error('Username not allowed. Only alphanumerics characters (uppercase and lowercase words), underscore and it must be between 5 and 15 characters')
|
return new Error('Username not allowed. Only alphanumerics characters (uppercase and lowercase words), underscore and it must be between 5 and 15 characters')
|
||||||
}
|
}
|
||||||
|
|
||||||
if (await prisma.user.findFirst({ where: { username } })) {
|
if (!validator.isEmail(email)) {
|
||||||
|
return new Error('Invalid email format')
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((await prisma.user.findFirst({ where: { username } })) != null) {
|
||||||
return new Error('Username already in use')
|
return new Error('Username already in use')
|
||||||
}
|
}
|
||||||
|
|
||||||
if (await prisma.user.findFirst({ where: { email } })) {
|
if ((await prisma.user.findFirst({ where: { email } })) != null) {
|
||||||
return new Error('Email already in use')
|
return new Error('Email already in use')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -28,7 +33,7 @@ async function userSignupService ({ username, email, password }) {
|
||||||
password: hashedPassword
|
password: hashedPassword
|
||||||
},
|
},
|
||||||
select: {
|
select: {
|
||||||
id: true,
|
displayName: true,
|
||||||
username: true,
|
username: true,
|
||||||
createdAt: true
|
createdAt: true
|
||||||
}
|
}
|
0
src/tests/post/create-post.spec.ts
Normal file
0
src/tests/post/create-post.spec.ts
Normal file
|
@ -1,6 +1,6 @@
|
||||||
import request from 'supertest'
|
import request from 'supertest'
|
||||||
import prisma from '../../prisma/client.js'
|
import prisma from '../../../prisma/client'
|
||||||
import app from '../app.js'
|
import app from '../../app'
|
||||||
|
|
||||||
describe('POST /user/auth', () => {
|
describe('POST /user/auth', () => {
|
||||||
beforeAll(async () => {
|
beforeAll(async () => {
|
|
@ -1,6 +1,6 @@
|
||||||
import request from 'supertest'
|
import request from 'supertest'
|
||||||
import prisma from '../../prisma/client.js'
|
import prisma from '../../../prisma/client'
|
||||||
import app from '../app.js'
|
import app from '../../app'
|
||||||
|
|
||||||
const mockUser = {
|
const mockUser = {
|
||||||
username: 'username11',
|
username: 'username11',
|
||||||
|
@ -12,7 +12,7 @@ describe('POST /user/create', () => {
|
||||||
it('should respond with a 200 status code', async () => {
|
it('should respond with a 200 status code', async () => {
|
||||||
const response = await request(app).post('/user/create').send(mockUser).expect(200)
|
const response = await request(app).post('/user/create').send(mockUser).expect(200)
|
||||||
|
|
||||||
expect(response.body).toHaveProperty('id')
|
expect(response.body).toHaveProperty('displayName')
|
||||||
expect(response.body).toHaveProperty('username')
|
expect(response.body).toHaveProperty('username')
|
||||||
expect(response.body).toHaveProperty('createdAt')
|
expect(response.body).toHaveProperty('createdAt')
|
||||||
})
|
})
|
111
tsconfig.json
Normal file
111
tsconfig.json
Normal file
|
@ -0,0 +1,111 @@
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
/* Visit https://aka.ms/tsconfig to read more about this file */
|
||||||
|
/* Projects */
|
||||||
|
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
|
||||||
|
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
|
||||||
|
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
|
||||||
|
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
|
||||||
|
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
|
||||||
|
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
|
||||||
|
/* Language and Environment */
|
||||||
|
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
|
||||||
|
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
|
||||||
|
// "jsx": "preserve", /* Specify what JSX code is generated. */
|
||||||
|
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
|
||||||
|
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
|
||||||
|
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
|
||||||
|
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
|
||||||
|
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
|
||||||
|
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
|
||||||
|
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
|
||||||
|
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
|
||||||
|
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
|
||||||
|
/* Modules */
|
||||||
|
"module": "commonjs", /* Specify what module code is generated. */
|
||||||
|
"rootDir": "./", /* Specify the root folder within your source files. */
|
||||||
|
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
|
||||||
|
"baseUrl": "./src", /* Specify the base directory to resolve non-relative module names. */
|
||||||
|
"paths": {
|
||||||
|
"@services/*": [
|
||||||
|
"services/*"
|
||||||
|
],
|
||||||
|
"@db/*": [
|
||||||
|
"../prisma/*"
|
||||||
|
]
|
||||||
|
}, /* Specify a set of entries that re-map imports to additional lookup locations. */
|
||||||
|
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
|
||||||
|
"typeRoots": [
|
||||||
|
"src/@types",
|
||||||
|
"node_modules/@types"
|
||||||
|
], /* Specify multiple folders that act like './node_modules/@types'. */
|
||||||
|
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
|
||||||
|
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||||
|
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
|
||||||
|
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
|
||||||
|
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
|
||||||
|
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
|
||||||
|
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
|
||||||
|
// "resolveJsonModule": true, /* Enable importing .json files. */
|
||||||
|
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
|
||||||
|
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
|
||||||
|
/* JavaScript Support */
|
||||||
|
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
|
||||||
|
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
|
||||||
|
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
|
||||||
|
/* Emit */
|
||||||
|
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
|
||||||
|
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
|
||||||
|
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
|
||||||
|
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
|
||||||
|
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
|
||||||
|
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
|
||||||
|
"outDir": "./dist", /* Specify an output folder for all emitted files. */
|
||||||
|
"removeComments": true, /* Disable emitting comments. */
|
||||||
|
// "noEmit": true, /* Disable emitting files from a compilation. */
|
||||||
|
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
|
||||||
|
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
|
||||||
|
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
|
||||||
|
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
|
||||||
|
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||||
|
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
|
||||||
|
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
|
||||||
|
// "newLine": "crlf", /* Set the newline character for emitting files. */
|
||||||
|
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
|
||||||
|
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
|
||||||
|
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
|
||||||
|
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
|
||||||
|
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
|
||||||
|
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
|
||||||
|
/* Interop Constraints */
|
||||||
|
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
|
||||||
|
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
|
||||||
|
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
|
||||||
|
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
|
||||||
|
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
|
||||||
|
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
|
||||||
|
/* Type Checking */
|
||||||
|
"strict": true, /* Enable all strict type-checking options. */
|
||||||
|
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
|
||||||
|
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
|
||||||
|
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
|
||||||
|
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
|
||||||
|
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
|
||||||
|
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
|
||||||
|
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
|
||||||
|
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
|
||||||
|
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
|
||||||
|
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
|
||||||
|
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
|
||||||
|
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
|
||||||
|
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
|
||||||
|
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
|
||||||
|
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
|
||||||
|
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
|
||||||
|
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
|
||||||
|
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
|
||||||
|
/* Completeness */
|
||||||
|
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
|
||||||
|
"skipLibCheck": true /* Skip type checking all .d.ts files. */
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue