diff --git a/src/@types/express.d.ts b/src/@types/express.d.ts index a1089d1..58b2b3f 100644 --- a/src/@types/express.d.ts +++ b/src/@types/express.d.ts @@ -1,12 +1,11 @@ -/* eslint-disable */ -import * as express from 'express' +import * as express from "express"; declare global { namespace Express { namespace Multer { interface File { - location: string - key: string + location: string; + key: string; } } } diff --git a/src/__tests__/post/post-create.test.ts b/src/__tests__/post/post-create.test.ts index 60c81b4..7e519f2 100644 --- a/src/__tests__/post/post-create.test.ts +++ b/src/__tests__/post/post-create.test.ts @@ -1,30 +1,29 @@ -import app from '../../app' -import { expect, describe, beforeAll, afterAll, it } from 'vitest' -import request from 'supertest' -import signUpNewUser from '../utils/create-user' -import deleteUser from '../utils/delete-user' -import type User from 'interfaces/user' +import app from "../../app"; +import { expect, describe, beforeAll, afterAll, it } from "vitest"; +import request from "supertest"; +import signUpNewUser from "../utils/create-user"; +import deleteUser from "../utils/delete-user"; +import type User from "interfaces/user"; -let user: User +let user: User; -describe('POST /post/create', () => { +describe("POST /post/create", () => { beforeAll(async () => { - user = await signUpNewUser() - }) + user = await signUpNewUser(); + }); afterAll(async () => { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - await deleteUser(user.username!) - }) + await deleteUser(user.username as string); // TODO: need to take a look at this + }); - it('should respond with 200 status code if the user send the token and the content', async () => { + it("should respond with 200 status code if the user send the token and the content", async () => { const response = await request(app) - .post('/post/create') + .post("/post/create") .send({ - content: 'Hello world', + content: "Hello world", }) - .set('Authorization', `Bearer ${user.token ?? ''}`) - .expect(200) + .set("Authorization", `Bearer ${user.token ?? ""}`) + .expect(200); expect(response.body).toEqual( expect.objectContaining({ @@ -33,13 +32,13 @@ describe('POST /post/create', () => { authorId: expect.any(String), createdAt: expect.any(String), updatedAt: expect.any(String), - }), - ) - }) + }) + ); + }); - it('should respond with 400 status code if the user send no token', async () => { - const response = await request(app).post('/post/create').expect(401) + it("should respond with 400 status code if the user send no token", async () => { + const response = await request(app).post("/post/create").expect(401); - expect(response.body).toHaveProperty('error') - }) -}) + expect(response.body).toHaveProperty("error"); + }); +}); diff --git a/src/__tests__/post/post-delete.test.ts b/src/__tests__/post/post-delete.test.ts index f886e4d..f7fd13e 100644 --- a/src/__tests__/post/post-delete.test.ts +++ b/src/__tests__/post/post-delete.test.ts @@ -1,37 +1,36 @@ -import app from '../../app' -import { describe, beforeAll, afterAll, it } from 'vitest' -import request from 'supertest' -import signUpNewUser from '../utils/create-user' -import deleteUser from '../utils/delete-user' -import type User from 'interfaces/user' +import app from "../../app"; +import { describe, beforeAll, afterAll, it } from "vitest"; +import request from "supertest"; +import signUpNewUser from "../utils/create-user"; +import deleteUser from "../utils/delete-user"; +import type User from "interfaces/user"; -let user: User +let user: User; -describe('DELETE /post/delete', () => { +describe("DELETE /post/delete", () => { beforeAll(async () => { - user = await signUpNewUser() - }) + user = await signUpNewUser(); + }); afterAll(async () => { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - await deleteUser(user.username!) - }) + await deleteUser(user.username as string); // TODO: here too + }); - it('should delete the post successfully', async () => { + it("should delete the post successfully", async () => { const response = await request(app) - .post('/post/create') + .post("/post/create") .send({ - content: 'lorem ipsum', + content: "lorem ipsum", }) - .set('Authorization', `Bearer ${user.token ?? ''}`) - .expect(200) + .set("Authorization", `Bearer ${user.token ?? ""}`) + .expect(200); await request(app) - .post('/post/delete') + .post("/post/delete") .send({ postId: response.body.id, }) - .set('Authorization', `Bearer ${user.token ?? ''}`) - .expect(200) - }) -}) + .set("Authorization", `Bearer ${user.token ?? ""}`) + .expect(200); + }); +}); diff --git a/src/__tests__/post/post-info.test.ts b/src/__tests__/post/post-info.test.ts index 61dfa00..478210d 100644 --- a/src/__tests__/post/post-info.test.ts +++ b/src/__tests__/post/post-info.test.ts @@ -1,40 +1,39 @@ -import app from '../../app' -import { expect, describe, beforeAll, afterAll, it } from 'vitest' -import request from 'supertest' -import signUpNewUser from '../utils/create-user' -import deleteUser from '../utils/delete-user' -import type User from 'interfaces/user' +import app from "../../app"; +import { expect, describe, beforeAll, afterAll, it } from "vitest"; +import request from "supertest"; +import signUpNewUser from "../utils/create-user"; +import deleteUser from "../utils/delete-user"; +import type User from "interfaces/user"; -let postId: string +let postId: string; -let user: User +let user: User; -describe('POST /post/info', () => { +describe("POST /post/info", () => { beforeAll(async () => { - user = await signUpNewUser() + user = await signUpNewUser(); - const token = user.token ?? '' + const token = user.token ?? ""; const post = await request(app) - .post('/post/create') + .post("/post/create") .send({ - content: 'Hello world', + content: "Hello world", }) - .set('Authorization', `Bearer ${token}`) - .expect(200) + .set("Authorization", `Bearer ${token}`) + .expect(200); - postId = post.body.id - }) + postId = post.body.id; + }); afterAll(async () => { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - await deleteUser(user.username!) - }) + await deleteUser(user.username as string); // TODO: here too btw + }); - it('should respond with 200 status code and return some info about the post', async () => { + it("should respond with 200 status code and return some info about the post", async () => { const response = await request(app) .get(`/post/info?id=${postId}`) - .expect(200) + .expect(200); expect(response.body).toEqual( expect.objectContaining({ @@ -43,13 +42,13 @@ describe('POST /post/info', () => { createdAt: expect.any(String), updatedAt: expect.any(String), author: expect.any(Object), - }), - ) - }) + }) + ); + }); - it('should respond with 400 status code if the post does not exists', async () => { - const response = await request(app).get('/post/info?id=abc').expect(400) + it("should respond with 400 status code if the post does not exists", async () => { + const response = await request(app).get("/post/info?id=abc").expect(400); - expect(response.body).toHaveProperty('error') - }) -}) + expect(response.body).toHaveProperty("error"); + }); +}); diff --git a/src/__tests__/post/post-update.test.ts b/src/__tests__/post/post-update.test.ts index 3cdde79..f5da9f8 100644 --- a/src/__tests__/post/post-update.test.ts +++ b/src/__tests__/post/post-update.test.ts @@ -1,47 +1,46 @@ -import app from '../../app' -import { expect, describe, beforeAll, afterAll, it } from 'vitest' -import request from 'supertest' -import signUpNewUser from '../utils/create-user' -import deleteUser from '../utils/delete-user' -import type User from 'interfaces/user' +import app from "../../app"; +import { expect, describe, beforeAll, afterAll, it } from "vitest"; +import request from "supertest"; +import signUpNewUser from "../utils/create-user"; +import deleteUser from "../utils/delete-user"; +import type User from "interfaces/user"; -let user: User +let user: User; -describe('PUT /post/update', () => { +describe("PUT /post/update", () => { beforeAll(async () => { - user = await signUpNewUser() - }) + user = await signUpNewUser(); + }); afterAll(async () => { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - await deleteUser(user.username!) - }) + await deleteUser(user.username as string); // TODO: well, here too + }); - it('should create a new post and update the content of it', async () => { + it("should create a new post and update the content of it", async () => { const post = await request(app) - .post('/post/create') + .post("/post/create") .send({ - content: 'Lorem', + content: "Lorem", }) - .set('Authorization', `Bearer ${user.token ?? ''}`) - .expect(200) + .set("Authorization", `Bearer ${user.token ?? ""}`) + .expect(200); - expect(post.body).toHaveProperty('id') + expect(post.body).toHaveProperty("id"); const fieldsToUpdate = { postId: post.body.id, - content: 'Lorem ipsum', - } + content: "Lorem ipsum", + }; const response = await request(app) - .put('/post/update') + .put("/post/update") .send(fieldsToUpdate) - .set('Authorization', `Bearer ${user.token ?? ''}`) - .expect(200) + .set("Authorization", `Bearer ${user.token ?? ""}`) + .expect(200); // Post content should be Lorem Ipsum if (post.body.content === response.body.content) { - throw new Error("Post didn't update") + throw new Error("Post didn't update"); } expect(response.body).toEqual( @@ -51,7 +50,7 @@ describe('PUT /post/update', () => { createdAt: expect.any(String), updatedAt: expect.any(String), author: expect.any(Object), - }), - ) - }) -}) + }) + ); + }); +}); diff --git a/src/__tests__/user/user-auth.test.ts b/src/__tests__/user/user-auth.test.ts index 8f56f63..3d6a4b8 100644 --- a/src/__tests__/user/user-auth.test.ts +++ b/src/__tests__/user/user-auth.test.ts @@ -1,46 +1,45 @@ -import app from '../../app' -import deleteUser from '../utils/delete-user' -import { expect, describe, beforeAll, afterAll, it } from 'vitest' -import request from 'supertest' -import signUpNewUser from '../utils/create-user' +import app from "../../app"; +import deleteUser from "../utils/delete-user"; +import { expect, describe, beforeAll, afterAll, it } from "vitest"; +import request from "supertest"; +import signUpNewUser from "../utils/create-user"; -import type User from 'interfaces/user' -let user: User +import type User from "interfaces/user"; +let user: User; -describe('POST /user/auth', () => { +describe("POST /user/auth", () => { beforeAll(async () => { - user = await signUpNewUser() - }) + user = await signUpNewUser(); + }); afterAll(async () => { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - await deleteUser(user.username!) - }) + await deleteUser(user.username as string); + }); - it('should respond with a error if the user does not exists', async () => { + it("should respond with a error if the user does not exists", async () => { const response = await request(app) - .post('/user/auth') - .send({ email: 'mm@mm.com', password: 'aa' }) - .expect(400) + .post("/user/auth") + .send({ email: "mm@mm.com", password: "aa" }) + .expect(400); - expect(response.body).toHaveProperty('error') - expect(response.body.error).toBe('Invalid email or password') - }) + expect(response.body).toHaveProperty("error"); + expect(response.body.error).toBe("Invalid email or password"); + }); - it('should respond with a error if receive an invalid email or password', async () => { + it("should respond with a error if receive an invalid email or password", async () => { const response = await request(app) - .post('/user/auth') - .send({ email: user.email, password: 'fake_pass' }) - .expect(400) + .post("/user/auth") + .send({ email: user.email, password: "fake_pass" }) + .expect(400); - expect(response.body).toHaveProperty('error') - expect(response.body.error).toBe('Invalid email or password') - }) + expect(response.body).toHaveProperty("error"); + expect(response.body.error).toBe("Invalid email or password"); + }); - it('should respond with a error if receive an empty body', async () => { - const response = await request(app).post('/user/auth').send({}).expect(400) + it("should respond with a error if receive an empty body", async () => { + const response = await request(app).post("/user/auth").send({}).expect(400); - expect(response.body).toHaveProperty('error') - expect(response.body.error).toBe('Missing fields') - }) -}) + expect(response.body).toHaveProperty("error"); + expect(response.body.error).toBe("Missing fields"); + }); +}); diff --git a/src/__tests__/user/user-delete.test.ts b/src/__tests__/user/user-delete.test.ts index 45c1c0d..1606b4a 100644 --- a/src/__tests__/user/user-delete.test.ts +++ b/src/__tests__/user/user-delete.test.ts @@ -1,20 +1,20 @@ -import app from '../../app' -import { describe, beforeAll, it } from 'vitest' -import request from 'supertest' -import signUpNewUser from '../utils/create-user' -import type User from 'interfaces/user' +import app from "../../app"; +import { describe, beforeAll, it } from "vitest"; +import request from "supertest"; +import signUpNewUser from "../utils/create-user"; +import type User from "interfaces/user"; -let user: User +let user: User; -describe('DELETE /user/delete', () => { +describe("DELETE /user/delete", () => { beforeAll(async () => { - user = await signUpNewUser() - }) + user = await signUpNewUser(); + }); - it('should delete the user successfully', async () => { + it("should delete the user successfully", async () => { await request(app) - .post('/user/delete') - .set('Authorization', `Bearer ${user.token ?? ''}`) - .expect(200) - }) -}) + .post("/user/delete") + .set("Authorization", `Bearer ${user.token ?? ""}`) + .expect(200); + }); +}); diff --git a/src/__tests__/user/user-info.test.ts b/src/__tests__/user/user-info.test.ts index 43c7269..93cfa43 100644 --- a/src/__tests__/user/user-info.test.ts +++ b/src/__tests__/user/user-info.test.ts @@ -1,38 +1,38 @@ -import app from '../../app' -import { expect, describe, beforeAll, afterAll, it } from 'vitest' -import request from 'supertest' -import deleteUser from '../utils/delete-user' -import signUpNewUser from '../utils/create-user' -import type User from 'interfaces/user' +import app from "../../app"; +import { expect, describe, beforeAll, afterAll, it } from "vitest"; +import request from "supertest"; +import deleteUser from "../utils/delete-user"; +import signUpNewUser from "../utils/create-user"; +import type User from "interfaces/user"; -let user: User +let user: User; -describe('POST /user/info', () => { +describe("POST /user/info", () => { beforeAll(async () => { - user = await signUpNewUser() - }) + user = await signUpNewUser(); + }); afterAll(async () => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - await deleteUser(user.username!) - }) + await deleteUser(user.username as string); + }); - it('should respond with 200 status code and return the user data', async () => { + it("should respond with 200 status code and return the user data", async () => { const response = await request(app) - .get(`/user/info?u=${user.username ?? ''}`) - .expect(200) + .get(`/user/info?u=${user.username ?? ""}`) + .expect(200); - expect(response.body).toHaveProperty('profileImage') - expect(response.body).toHaveProperty('displayName') - expect(response.body).toHaveProperty('username') - expect(response.body).toHaveProperty('createdAt') - expect(response.body).toHaveProperty('posts') - expect(response.body).toHaveProperty('likedPosts') - }) + expect(response.body).toHaveProperty("profileImage"); + expect(response.body).toHaveProperty("displayName"); + expect(response.body).toHaveProperty("username"); + expect(response.body).toHaveProperty("createdAt"); + expect(response.body).toHaveProperty("posts"); + expect(response.body).toHaveProperty("likedPosts"); + }); - it('should respond with 400 status code if the user send no username', async () => { - const response = await request(app).get('/user/info?u=').expect(400) + it("should respond with 400 status code if the user send no username", async () => { + const response = await request(app).get("/user/info?u=").expect(400); - expect(response.body).toHaveProperty('error') - }) -}) + expect(response.body).toHaveProperty("error"); + }); +}); diff --git a/src/__tests__/user/user-signup.test.ts b/src/__tests__/user/user-signup.test.ts index 7f47832..f00552a 100644 --- a/src/__tests__/user/user-signup.test.ts +++ b/src/__tests__/user/user-signup.test.ts @@ -1,46 +1,46 @@ -import app from '../../app' -import { describe, beforeAll, afterAll, it } from 'vitest' -import request from 'supertest' -import deleteUser from '../utils/delete-user' -import signUpNewUser from '../utils/create-user' -import type User from 'interfaces/user' +import app from "../../app"; +import { describe, beforeAll, afterAll, it } from "vitest"; +import request from "supertest"; +import deleteUser from "../utils/delete-user"; +import signUpNewUser from "../utils/create-user"; +import type User from "interfaces/user"; -let user: User +let user: User; -describe('POST /user/signup', () => { +describe("POST /user/signup", () => { beforeAll(async () => { - user = await signUpNewUser() - delete user.token - }) + user = await signUpNewUser(); + user.token = undefined; + }); afterAll(async () => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - await deleteUser(user.username!) - }) + await deleteUser(user.username as string); + }); - it('should respond with a 400 status code if sent any invalid data', async () => { + it("should respond with a 400 status code if sent any invalid data", async () => { await request(app) - .post('/user/signup') + .post("/user/signup") .send({ - username: 'username12@', + username: "username12@", email: user.email, password: user.password, }) - .expect(400) - }) + .expect(400); + }); - it('should respond with a 400 status code for an existing username or email', async () => { + it("should respond with a 400 status code for an existing username or email", async () => { await request(app) - .post('/user/signup') + .post("/user/signup") .send({ username: user.username, email: user.email, password: user.password, }) - .expect(400) - }) + .expect(400); + }); - it('should respond with a 400 status code if receive an empty body', async () => { - await request(app).post('/user/signup').send({}).expect(400) - }) -}) + it("should respond with a 400 status code if receive an empty body", async () => { + await request(app).post("/user/signup").send({}).expect(400); + }); +}); diff --git a/src/__tests__/utils/create-user.ts b/src/__tests__/utils/create-user.ts index 396154f..d1df9e5 100644 --- a/src/__tests__/utils/create-user.ts +++ b/src/__tests__/utils/create-user.ts @@ -1,37 +1,37 @@ -import app from '../../app' -import request from 'supertest' -import { faker } from '@faker-js/faker' -import type userPayload from '../../interfaces/user' +import app from "../../app"; +import request from "supertest"; +import { faker } from "@faker-js/faker"; +import type userPayload from "../../interfaces/user"; async function signUpNewUser(): Promise { // To avoid conflicts with existing usernames or emails - const username = faker.internet.userName({ lastName: 'doe' }).toLowerCase() - const email = faker.internet.email() - const password = faker.internet.password() + '@1' + const username = faker.internet.userName({ lastName: "doe" }).toLowerCase(); + const email = faker.internet.email(); + const password = `${faker.internet.password()}@1`; await request(app) - .post('/user/signup') + .post("/user/signup") .send({ username, email, password, }) - .expect(200) + .expect(200); const response = await request(app) - .post('/user/auth') + .post("/user/auth") .send({ email, password, }) - .expect(200) + .expect(200); return { username, email, password, token: response.body.token, - } + }; } -export default signUpNewUser +export default signUpNewUser; diff --git a/src/__tests__/utils/delete-user.ts b/src/__tests__/utils/delete-user.ts index b942afc..088e083 100644 --- a/src/__tests__/utils/delete-user.ts +++ b/src/__tests__/utils/delete-user.ts @@ -1,4 +1,4 @@ -import prisma from '../../clients/prisma-client' +import prisma from "../../clients/prisma-client"; export default async function deleteUser(username: string) { await prisma.post.deleteMany({ @@ -7,11 +7,11 @@ export default async function deleteUser(username: string) { username, }, }, - }) + }); await prisma.user.deleteMany({ where: { username, }, - }) + }); } diff --git a/src/app.ts b/src/app.ts index 8f2ab0c..f3c1eda 100644 --- a/src/app.ts +++ b/src/app.ts @@ -1,49 +1,49 @@ -import 'dotenv/config' +import "dotenv/config"; -import compression from 'compression' -import cors from 'cors' -import express from 'express' -import limiter from 'middlewares/rate-limit' -import morganMiddleware from 'middlewares/morgan' -import router from './routes' -import swaggerUI from 'swagger-ui-express' -import swaggerDocument from 'helpers/parse-swagger' -import swaggerConfig from 'config/swagger' +import compression from "compression"; +import cors from "cors"; +import express from "express"; +import limiter from "middlewares/rate-limit"; +import morganMiddleware from "middlewares/morgan"; +import router from "./routes"; +import swaggerUI from "swagger-ui-express"; +import swaggerDocument from "helpers/parse-swagger"; +import swaggerConfig from "config/swagger"; -const app = express() +const app = express(); // TODO: test socket io, emit notifications when create one. -app.use(express.json()) -app.use(express.urlencoded({ extended: true })) -app.use(morganMiddleware) -app.options('*', cors()) +app.use(express.json()); +app.use(express.urlencoded({ extended: true })); +app.use(morganMiddleware); +app.options("*", cors()); app.use( cors({ credentials: true, origin: process.env.CLIENT_URL, - methods: ['GET', 'POST', 'PUT'], + methods: ["GET", "POST", "PUT"], optionsSuccessStatus: 200, - }), -) -app.use(express.static('public')) -app.use(limiter) -app.use(router) + }) +); +app.use(express.static("public")); +app.use(limiter); +app.use(router); app.use( - '/docs', + "/docs", swaggerUI.serve, - swaggerUI.setup(swaggerDocument, swaggerConfig), -) -app.use(compression({ level: 9 })) + swaggerUI.setup(swaggerDocument, swaggerConfig) +); +app.use(compression({ level: 9 })); -app.get('/', function (_req, res) { - res.redirect('/docs') -}) +app.get("/", (_req, res) => { + res.redirect("/docs"); +}); app.use((_req, res) => { res.status(404).json({ - error: 'Endpoint not found', - }) -}) + error: "Endpoint not found", + }); +}); -export default app +export default app; diff --git a/src/clients/prisma-client.ts b/src/clients/prisma-client.ts index 4590932..b5bf6ce 100644 --- a/src/clients/prisma-client.ts +++ b/src/clients/prisma-client.ts @@ -1,5 +1,5 @@ -import { PrismaClient } from '@prisma/client' +import { PrismaClient } from "@prisma/client"; -const prisma = new PrismaClient() +const prisma = new PrismaClient(); -export default prisma +export default prisma; diff --git a/src/clients/redis-client.ts b/src/clients/redis-client.ts index 64aa564..ffb6092 100644 --- a/src/clients/redis-client.ts +++ b/src/clients/redis-client.ts @@ -1,27 +1,27 @@ -import logger from 'helpers/logger' -import { createClient, type RedisClientOptions } from 'redis' +import logger from "helpers/logger"; +import { createClient, type RedisClientOptions } from "redis"; -const redisPort = parseInt(process.env.REDIS_PORT ?? '6379', 10) -const redisHost = process.env.REDIS_HOST ?? '127.0.0.1' -const redisPassword = process.env.REDIS_PASSWORD ?? '' +const redisPort = parseInt(process.env.REDIS_PORT ?? "6379", 10); +const redisHost = process.env.REDIS_HOST ?? "127.0.0.1"; +const redisPassword = process.env.REDIS_PASSWORD ?? ""; const redisConfig: RedisClientOptions = { url: `redis://:${redisPassword}@${redisHost}:${redisPort}/0`, -} +}; -const redis = createClient(redisConfig) +const redis = createClient(redisConfig); redis .connect() .then(() => { - logger.info('Successfully connected to Redis') + logger.info("Successfully connected to Redis"); }) .catch((e: Error) => { - logger.error(`Error while connecting to Redis: ${e.message}`) - }) + logger.error(`Error while connecting to Redis: ${e.message}`); + }); -redis.on('error', async (e: Error) => { - logger.error(`Error in Redis client: ${e.message}`) -}) +redis.on("error", async (e: Error) => { + logger.error(`Error in Redis client: ${e.message}`); +}); -export default redis +export default redis; diff --git a/src/clients/s3-client.ts b/src/clients/s3-client.ts index b0e955f..a68ecce 100644 --- a/src/clients/s3-client.ts +++ b/src/clients/s3-client.ts @@ -1,24 +1,24 @@ -import { S3Client } from '@aws-sdk/client-s3' -import logger from 'helpers/logger' +import { S3Client } from "@aws-sdk/client-s3"; +import logger from "helpers/logger"; -let s3: S3Client +let s3: S3Client; -if (process.env.NODE_ENV === 'development') { - logger.info('Using Localstack services instead of AWS.') +if (process.env.NODE_ENV === "development") { + logger.info("Using Localstack services instead of AWS."); s3 = new S3Client({ credentials: { - accessKeyId: process.env.AWS_ACCESS_KEY_ID ?? '', - secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY ?? '', + accessKeyId: process.env.AWS_ACCESS_KEY_ID ?? "", + secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY ?? "", }, - endpoint: 'http://127.0.0.1:4566', // Uses localstack instead of aws, make sure to create the bucket first with public-read acl - }) + endpoint: "http://127.0.0.1:4566", // Uses localstack instead of aws, make sure to create the bucket first with public-read acl + }); } else { s3 = new S3Client({ credentials: { - accessKeyId: process.env.AWS_ACCESS_KEY_ID ?? '', - secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY ?? '', + accessKeyId: process.env.AWS_ACCESS_KEY_ID ?? "", + secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY ?? "", }, - }) + }); } -export default s3 +export default s3; diff --git a/src/config/multer.ts b/src/config/multer.ts index 17b3fa0..8bfedb9 100644 --- a/src/config/multer.ts +++ b/src/config/multer.ts @@ -1,45 +1,44 @@ -import multer from 'multer' -import { type Request } from 'express' -import path from 'path' -import s3 from 'clients/s3-client' -import multerS3 from 'multer-s3' +import multer from "multer"; +import { type Request } from "express"; +import path from "path"; +import s3 from "clients/s3-client"; +import multerS3 from "multer-s3"; -const tempFolder = path.resolve(__dirname, '..', '..', 'temp', 'uploads') +const tempFolder = path.resolve(__dirname, "..", "..", "temp", "uploads"); const storageTypes = { local: multer.diskStorage({ destination: (req: Request, file: Express.Multer.File, callback) => { - callback(null, tempFolder) + callback(null, tempFolder); }, filename: (req: Request, file: Express.Multer.File, callback) => { - /* eslint-disable */ - const folder = req.body.isProfilePicture ? 'profile_images' : 'media' - const fileName: string = `${folder}/${req.res?.locals.user.id}.webp` + const folder = req.body.isProfilePicture ? "profile_images" : "media"; + const fileName: string = `${folder}/${req.res?.locals.user.id}.webp`; - callback(null, fileName) + callback(null, fileName); }, }), s3: multerS3({ s3, - bucket: process.env.AWS_BUCKET ?? '', + bucket: process.env.AWS_BUCKET ?? "", contentType: multerS3.AUTO_CONTENT_TYPE, - acl: 'public-read', + acl: "public-read", key: (req: Request, file: Express.Multer.File, callback) => { - let folder + let folder: string; - if (req.body.isProfilePicture === 'true') { - folder = 'profile_images' + if (req.body.isProfilePicture === "true") { + folder = "profile_images"; } else { - folder = 'media' + folder = "media"; } - const fileName: string = `${folder}/${req.res?.locals.user.id}.jpg` - callback(null, fileName) + const fileName: string = `${folder}/${req.res?.locals.user.id}.jpg`; + callback(null, fileName); }, }), -} +}; const multerConfig = { dest: tempFolder, @@ -50,16 +49,16 @@ const multerConfig = { fileFilter: ( req: Request, file: Express.Multer.File, - callback: multer.FileFilterCallback, + callback: multer.FileFilterCallback ) => { - const allowedMimes = ['image/jpeg', 'image/png'] + const allowedMimes = ["image/jpeg", "image/png"]; if (allowedMimes.includes(file.mimetype)) { - callback(null, true) + callback(null, true); } else { - callback(new Error('Filetype not allowed')) + callback(new Error("Filetype not allowed")); } }, -} +}; -export default multerConfig +export default multerConfig; diff --git a/src/config/swagger.ts b/src/config/swagger.ts index 749f089..a188d1c 100644 --- a/src/config/swagger.ts +++ b/src/config/swagger.ts @@ -1,9 +1,9 @@ -import type { SwaggerUiOptions } from 'swagger-ui-express' +import type { SwaggerUiOptions } from "swagger-ui-express"; const swaggerConfig: SwaggerUiOptions = { - customCssUrl: '/swagger-ui.css', - customSiteTitle: 'Project Knedita Docs', - customfavIcon: '/favicon.png', -} + customCssUrl: "/swagger-ui.css", + customSiteTitle: "Project Knedita Docs", + customfavIcon: "/favicon.png", +}; -export default swaggerConfig +export default swaggerConfig; diff --git a/src/controllers/comments-router.ts b/src/controllers/comments-router.ts index c1eea9f..7b787c0 100644 --- a/src/controllers/comments-router.ts +++ b/src/controllers/comments-router.ts @@ -1,22 +1,22 @@ -import { Router } from 'express' +import { Router } from "express"; // Controllers -import comments from './comments' +import comments from "./comments"; // Middlewares -import authenticated from 'middlewares/authenticated' +import authenticated from "middlewares/authenticated"; -const commentsRouter = Router() +const commentsRouter = Router(); // GET -commentsRouter.get('/fetch-likes', comments.fetchLikes) -commentsRouter.get('/info', comments.fetch) +commentsRouter.get("/fetch-likes", comments.fetchLikes); +commentsRouter.get("/info", comments.fetch); // POST -commentsRouter.post('/create', authenticated, comments.create) -commentsRouter.post('/delete', authenticated, comments.delete) +commentsRouter.post("/create", authenticated, comments.create); +commentsRouter.post("/delete", authenticated, comments.delete); // PUT -commentsRouter.put('/update', authenticated, comments.update) +commentsRouter.put("/update", authenticated, comments.update); -export default commentsRouter +export default commentsRouter; diff --git a/src/controllers/comments/create.ts b/src/controllers/comments/create.ts index afa03d9..087176c 100644 --- a/src/controllers/comments/create.ts +++ b/src/controllers/comments/create.ts @@ -1,28 +1,28 @@ -import comment from 'services/comments' -import type { Request, Response } from 'express' -import { badRequest } from 'helpers/http-errors' -import handleResponse from 'helpers/handle-response' +import comment from "services/comments"; +import type { Request, Response } from "express"; +import { badRequest } from "helpers/http-errors"; +import handleResponse from "helpers/handle-response"; async function commentCreateController( req: Request, - res: Response, + res: Response ): Promise { - const { content, postId } = req.body - const id = res.locals.user.id + const { content, postId } = req.body; + const id = res.locals.user.id; if (postId === undefined) { - badRequest(res, 'Expected post id') - return + badRequest(res, "Expected post id"); + return; } if (content === undefined) { - badRequest(res, 'Expected comment content') - return + badRequest(res, "Expected comment content"); + return; } - const result = await comment.create(postId, content, id) + const result = await comment.create(postId, content, id); - handleResponse(res, result) + handleResponse(res, result); } -export default commentCreateController +export default commentCreateController; diff --git a/src/controllers/comments/delete.ts b/src/controllers/comments/delete.ts index c3d6918..3a68a9f 100644 --- a/src/controllers/comments/delete.ts +++ b/src/controllers/comments/delete.ts @@ -1,23 +1,23 @@ -import comment from 'services/comments' -import type { Request, Response } from 'express' -import { badRequest } from 'helpers/http-errors' -import handleResponse from 'helpers/handle-response' +import comment from "services/comments"; +import type { Request, Response } from "express"; +import { badRequest } from "helpers/http-errors"; +import handleResponse from "helpers/handle-response"; async function commentDeleteController( req: Request, - res: Response, + res: Response ): Promise { - const { commentId } = req.body - const id = res.locals.user.id + const { commentId } = req.body; + const id = res.locals.user.id; if (commentId === undefined) { - badRequest(res, 'Expected comment id') - return + badRequest(res, "Expected comment id"); + return; } - const result = await comment.delete(commentId, id) + const result = await comment.delete(commentId, id); - handleResponse(res, result) + handleResponse(res, result); } -export default commentDeleteController +export default commentDeleteController; diff --git a/src/controllers/comments/fetch-info.ts b/src/controllers/comments/fetch-info.ts index 1dfc3e3..56efae2 100644 --- a/src/controllers/comments/fetch-info.ts +++ b/src/controllers/comments/fetch-info.ts @@ -1,22 +1,22 @@ -import comment from 'services/comments' -import type { Request, Response } from 'express' -import { badRequest } from 'helpers/http-errors' -import handleResponse from 'helpers/handle-response' +import comment from "services/comments"; +import type { Request, Response } from "express"; +import { badRequest } from "helpers/http-errors"; +import handleResponse from "helpers/handle-response"; async function commentFetchController( req: Request, - res: Response, + res: Response ): Promise { - const commentId = req.query.id as string + const commentId = req.query.id as string; if (commentId === undefined) { - badRequest(res, 'Expected comment id') - return + badRequest(res, "Expected comment id"); + return; } - const result = await comment.fetch(commentId) + const result = await comment.fetch(commentId); - handleResponse(res, result) + handleResponse(res, result); } -export default commentFetchController +export default commentFetchController; diff --git a/src/controllers/comments/fetch-likes.ts b/src/controllers/comments/fetch-likes.ts index f3532b0..266571f 100644 --- a/src/controllers/comments/fetch-likes.ts +++ b/src/controllers/comments/fetch-likes.ts @@ -1,22 +1,22 @@ -import comment from 'services/comments' -import type { Request, Response } from 'express' -import { badRequest } from 'helpers/http-errors' -import handleResponse from 'helpers/handle-response' +import comment from "services/comments"; +import type { Request, Response } from "express"; +import { badRequest } from "helpers/http-errors"; +import handleResponse from "helpers/handle-response"; async function commentFetchLikesController( req: Request, - res: Response, + res: Response ): Promise { - const commentId = req.query.id as string + const commentId = req.query.id as string; if (commentId === undefined) { - badRequest(res, 'Expected comment id') - return + badRequest(res, "Expected comment id"); + return; } - const result = await comment.fetchLikes(commentId) + const result = await comment.fetchLikes(commentId); - handleResponse(res, result) + handleResponse(res, result); } -export default commentFetchLikesController +export default commentFetchLikesController; diff --git a/src/controllers/comments/index.ts b/src/controllers/comments/index.ts index 7007a70..8db4f41 100644 --- a/src/controllers/comments/index.ts +++ b/src/controllers/comments/index.ts @@ -1,8 +1,8 @@ -import commentCreateController from './create' -import commentDeleteController from './delete' -import commentFetchController from './fetch-info' -import commentFetchLikesController from './fetch-likes' -import commentUpdateController from './update' +import commentCreateController from "./create"; +import commentDeleteController from "./delete"; +import commentFetchController from "./fetch-info"; +import commentFetchLikesController from "./fetch-likes"; +import commentUpdateController from "./update"; const comments = { create: commentCreateController, @@ -10,6 +10,6 @@ const comments = { fetch: commentFetchController, fetchLikes: commentFetchLikesController, update: commentUpdateController, -} as const +} as const; -export default comments +export default comments; diff --git a/src/controllers/comments/update.ts b/src/controllers/comments/update.ts index 3a35178..bc39c10 100644 --- a/src/controllers/comments/update.ts +++ b/src/controllers/comments/update.ts @@ -1,28 +1,28 @@ -import comment from 'services/comments' -import type { Request, Response } from 'express' -import { badRequest } from 'helpers/http-errors' -import handleResponse from 'helpers/handle-response' +import comment from "services/comments"; +import type { Request, Response } from "express"; +import { badRequest } from "helpers/http-errors"; +import handleResponse from "helpers/handle-response"; async function commentUpdateController( req: Request, - res: Response, + res: Response ): Promise { - const { commentId, content } = req.body - const id = res.locals.user.id + const { commentId, content } = req.body; + const id = res.locals.user.id; if (commentId === undefined) { - badRequest(res, 'Expected comment content') - return + badRequest(res, "Expected comment content"); + return; } if (content === undefined) { - badRequest(res, 'Expected content to update') - return + badRequest(res, "Expected content to update"); + return; } - const result = await comment.update(content, id, commentId) + const result = await comment.update(content, id, commentId); - handleResponse(res, result) + handleResponse(res, result); } -export default commentUpdateController +export default commentUpdateController; diff --git a/src/controllers/posts-router.ts b/src/controllers/posts-router.ts index f068433..4469191 100644 --- a/src/controllers/posts-router.ts +++ b/src/controllers/posts-router.ts @@ -1,22 +1,22 @@ -import { Router } from 'express' +import { Router } from "express"; // Controllers -import post from './posts' +import post from "./posts"; // Middlewares -import authenticated from 'middlewares/authenticated' +import authenticated from "middlewares/authenticated"; -const postsRouter = Router() +const postsRouter = Router(); // GET -postsRouter.get('/fetch-likes', post.fetchLikes) -postsRouter.get('/info', post.fetch) +postsRouter.get("/fetch-likes", post.fetchLikes); +postsRouter.get("/info", post.fetch); // POST -postsRouter.post('/create', authenticated, post.create) -postsRouter.post('/delete', authenticated, post.delete) +postsRouter.post("/create", authenticated, post.create); +postsRouter.post("/delete", authenticated, post.delete); // PUT -postsRouter.put('/update', authenticated, post.update) +postsRouter.put("/update", authenticated, post.update); -export default postsRouter +export default postsRouter; diff --git a/src/controllers/posts/create.ts b/src/controllers/posts/create.ts index 20b15bf..af8532e 100644 --- a/src/controllers/posts/create.ts +++ b/src/controllers/posts/create.ts @@ -1,23 +1,23 @@ -import post from 'services/posts' -import type { Request, Response } from 'express' -import { badRequest } from 'helpers/http-errors' -import handleResponse from 'helpers/handle-response' +import post from "services/posts"; +import type { Request, Response } from "express"; +import { badRequest } from "helpers/http-errors"; +import handleResponse from "helpers/handle-response"; async function postCreateController( req: Request, - res: Response, + res: Response ): Promise { - const { content } = req.body - const id = res.locals.user.id + const { content } = req.body; + const id = res.locals.user.id; if (content === undefined) { - badRequest(res, 'Expected post content') - return + badRequest(res, "Expected post content"); + return; } - const result = await post.create(content, id) + const result = await post.create(content, id); - handleResponse(res, result) + handleResponse(res, result); } -export default postCreateController +export default postCreateController; diff --git a/src/controllers/posts/delete.ts b/src/controllers/posts/delete.ts index 93e286f..f3a10a7 100644 --- a/src/controllers/posts/delete.ts +++ b/src/controllers/posts/delete.ts @@ -1,23 +1,23 @@ -import post from 'services/posts' -import type { Request, Response } from 'express' -import { badRequest } from 'helpers/http-errors' -import handleResponse from 'helpers/handle-response' +import post from "services/posts"; +import type { Request, Response } from "express"; +import { badRequest } from "helpers/http-errors"; +import handleResponse from "helpers/handle-response"; async function postDeleteController( req: Request, - res: Response, + res: Response ): Promise { - const userId = res.locals.user.id - const postId = req.body.postId + const userId = res.locals.user.id; + const postId = req.body.postId; if (postId === undefined) { - badRequest(res, 'Missing post id') - return + badRequest(res, "Missing post id"); + return; } - const result = await post.delete(postId, userId) + const result = await post.delete(postId, userId); - handleResponse(res, result) + handleResponse(res, result); } -export default postDeleteController +export default postDeleteController; diff --git a/src/controllers/posts/fetch-info.ts b/src/controllers/posts/fetch-info.ts index 4fdf774..c510d4f 100644 --- a/src/controllers/posts/fetch-info.ts +++ b/src/controllers/posts/fetch-info.ts @@ -1,22 +1,22 @@ -import post from 'services/posts' -import type { Request, Response } from 'express' -import { badRequest } from 'helpers/http-errors' -import handleResponse from 'helpers/handle-response' +import post from "services/posts"; +import type { Request, Response } from "express"; +import { badRequest } from "helpers/http-errors"; +import handleResponse from "helpers/handle-response"; async function postFetchInfoController( req: Request, - res: Response, + res: Response ): Promise { - const id = req.query.id as string + const id = req.query.id as string; if (id === undefined) { - badRequest(res, 'Missing post id') - return + badRequest(res, "Missing post id"); + return; } - const result = await post.fetch(id) + const result = await post.fetch(id); - handleResponse(res, result) + handleResponse(res, result); } -export default postFetchInfoController +export default postFetchInfoController; diff --git a/src/controllers/posts/fetch-likes.ts b/src/controllers/posts/fetch-likes.ts index 88e203e..d0f212c 100644 --- a/src/controllers/posts/fetch-likes.ts +++ b/src/controllers/posts/fetch-likes.ts @@ -1,22 +1,22 @@ -import post from 'services/posts' -import type { Request, Response } from 'express' -import { badRequest } from 'helpers/http-errors' -import handleResponse from 'helpers/handle-response' +import post from "services/posts"; +import type { Request, Response } from "express"; +import { badRequest } from "helpers/http-errors"; +import handleResponse from "helpers/handle-response"; async function postFetchLikesController( req: Request, - res: Response, + res: Response ): Promise { - const id = req.query.id as string + const id = req.query.id as string; if (id === undefined) { - badRequest(res, 'Missing post id') - return + badRequest(res, "Missing post id"); + return; } - const result = await post.fetchLikes(id) + const result = await post.fetchLikes(id); - handleResponse(res, result) + handleResponse(res, result); } -export default postFetchLikesController +export default postFetchLikesController; diff --git a/src/controllers/posts/index.ts b/src/controllers/posts/index.ts index 204d675..58e74bd 100644 --- a/src/controllers/posts/index.ts +++ b/src/controllers/posts/index.ts @@ -1,8 +1,8 @@ -import postCreateController from './create' -import postDeleteController from './delete' -import postFetchInfoController from './fetch-info' -import postUpdateController from './update' -import postFetchLikesController from './fetch-likes' +import postCreateController from "./create"; +import postDeleteController from "./delete"; +import postFetchInfoController from "./fetch-info"; +import postUpdateController from "./update"; +import postFetchLikesController from "./fetch-likes"; const post = { create: postCreateController, @@ -10,6 +10,6 @@ const post = { fetch: postFetchInfoController, fetchLikes: postFetchLikesController, update: postUpdateController, -} as const +} as const; -export default post +export default post; diff --git a/src/controllers/posts/update.ts b/src/controllers/posts/update.ts index eb3220a..fc39cff 100644 --- a/src/controllers/posts/update.ts +++ b/src/controllers/posts/update.ts @@ -1,17 +1,17 @@ -import post from 'services/posts' -import type { Request, Response } from 'express' -import handleResponse from 'helpers/handle-response' +import post from "services/posts"; +import type { Request, Response } from "express"; +import handleResponse from "helpers/handle-response"; async function postUpdateController( req: Request, - res: Response, + res: Response ): Promise { - const { postId, content } = req.body - const userId = res.locals.user.id + const { postId, content } = req.body; + const userId = res.locals.user.id; - const result = await post.update(postId, content, userId) + const result = await post.update(postId, content, userId); - handleResponse(res, result) + handleResponse(res, result); } -export default postUpdateController +export default postUpdateController; diff --git a/src/controllers/users-router.ts b/src/controllers/users-router.ts index 434f85e..8380589 100644 --- a/src/controllers/users-router.ts +++ b/src/controllers/users-router.ts @@ -1,37 +1,37 @@ -import { Router } from 'express' +import { Router } from "express"; // Controllers -import user from './users' +import user from "./users"; // Middlewares -import authenticated from 'middlewares/authenticated' -import uploadFile from 'middlewares/upload-image' +import authenticated from "middlewares/authenticated"; +import uploadFile from "middlewares/upload-image"; -const usersRouter = Router() +const usersRouter = Router(); // GET -usersRouter.get('/fetch-posts', user.fetchPosts) -usersRouter.get('/info', user.fetchInfo) -usersRouter.get('/search', user.searchUser) +usersRouter.get("/fetch-posts", user.fetchPosts); +usersRouter.get("/info", user.fetchInfo); +usersRouter.get("/search", user.searchUser); // POST -usersRouter.post('/auth', user.auth) -usersRouter.post('/delete', authenticated, user.delete) -usersRouter.post('/me', authenticated, user.fetchUser) -usersRouter.post('/follow-user', authenticated, user.follow) -usersRouter.post('/like-comment', authenticated, user.likeComment) -usersRouter.post('/like-post', authenticated, user.likePost) -usersRouter.post('/signup', user.signup) +usersRouter.post("/auth", user.auth); +usersRouter.post("/delete", authenticated, user.delete); +usersRouter.post("/me", authenticated, user.fetchUser); +usersRouter.post("/follow-user", authenticated, user.follow); +usersRouter.post("/like-comment", authenticated, user.likeComment); +usersRouter.post("/like-post", authenticated, user.likePost); +usersRouter.post("/signup", user.signup); // PUT usersRouter.put( - '/profile-picture/upload', + "/profile-picture/upload", authenticated, uploadFile, - user.uploadPicture, -) -usersRouter.put('/update-email', authenticated, user.updateEmail) -usersRouter.put('/update-name', authenticated, user.updateName) -usersRouter.put('/update-password', authenticated, user.updatePassword) + user.uploadPicture +); +usersRouter.put("/update-email", authenticated, user.updateEmail); +usersRouter.put("/update-name", authenticated, user.updateName); +usersRouter.put("/update-password", authenticated, user.updatePassword); -export default usersRouter +export default usersRouter; diff --git a/src/controllers/users/auth.ts b/src/controllers/users/auth.ts index 68d57b0..8b500de 100644 --- a/src/controllers/users/auth.ts +++ b/src/controllers/users/auth.ts @@ -1,13 +1,13 @@ -import user from 'services/users' -import type { Request, Response } from 'express' -import handleResponse from 'helpers/handle-response' +import user from "services/users"; +import type { Request, Response } from "express"; +import handleResponse from "helpers/handle-response"; async function userAuthController(req: Request, res: Response): Promise { - const { email, password } = req.body + const { email, password } = req.body; - const result = await user.auth({ email, password }) + const result = await user.auth({ email, password }); - handleResponse(res, result) + handleResponse(res, result); } -export default userAuthController +export default userAuthController; diff --git a/src/controllers/users/delete.ts b/src/controllers/users/delete.ts index 9cbb032..8590ce2 100644 --- a/src/controllers/users/delete.ts +++ b/src/controllers/users/delete.ts @@ -1,15 +1,15 @@ -import user from 'services/users' -import type { Request, Response } from 'express' -import handleResponse from 'helpers/handle-response' +import user from "services/users"; +import type { Request, Response } from "express"; +import handleResponse from "helpers/handle-response"; async function userDeleteController( req: Request, - res: Response, + res: Response ): Promise { - const userId = res.locals.user.id - const result = await user.delete(userId) + const userId = res.locals.user.id; + const result = await user.delete(userId); - handleResponse(res, result) + handleResponse(res, result); } -export default userDeleteController +export default userDeleteController; diff --git a/src/controllers/users/fetch-info.ts b/src/controllers/users/fetch-info.ts index 3d999d9..c3c0c71 100644 --- a/src/controllers/users/fetch-info.ts +++ b/src/controllers/users/fetch-info.ts @@ -1,22 +1,22 @@ -import user from 'services/users' -import type { Request, Response } from 'express' -import { badRequest } from 'helpers/http-errors' -import handleResponse from 'helpers/handle-response' +import user from "services/users"; +import type { Request, Response } from "express"; +import { badRequest } from "helpers/http-errors"; +import handleResponse from "helpers/handle-response"; async function userFetchInfoController( req: Request, - res: Response, + res: Response ): Promise { - const username = req.query.u as string + const username = req.query.u as string; if (username === undefined) { - badRequest(res, 'Missing username') - return + badRequest(res, "Missing username"); + return; } - const result = await user.fetchInfo(username.toLowerCase()) + const result = await user.fetchInfo(username.toLowerCase()); - handleResponse(res, result) + handleResponse(res, result); } -export default userFetchInfoController +export default userFetchInfoController; diff --git a/src/controllers/users/fetch-posts.ts b/src/controllers/users/fetch-posts.ts index f3eb9ae..03b393a 100644 --- a/src/controllers/users/fetch-posts.ts +++ b/src/controllers/users/fetch-posts.ts @@ -1,22 +1,22 @@ -import user from 'services/users' -import type { Request, Response } from 'express' -import { badRequest } from 'helpers/http-errors' -import handleResponse from 'helpers/handle-response' +import user from "services/users"; +import type { Request, Response } from "express"; +import { badRequest } from "helpers/http-errors"; +import handleResponse from "helpers/handle-response"; async function userFetchPostsController( req: Request, - res: Response, + res: Response ): Promise { - const username = req.query.u as string + const username = req.query.u as string; if (username === undefined) { - badRequest(res, 'Missing username') - return + badRequest(res, "Missing username"); + return; } - const result = await user.fetchPosts(username) + const result = await user.fetchPosts(username); - handleResponse(res, result) + handleResponse(res, result); } -export default userFetchPostsController +export default userFetchPostsController; diff --git a/src/controllers/users/fetch-user.ts b/src/controllers/users/fetch-user.ts index 788c003..8478208 100644 --- a/src/controllers/users/fetch-user.ts +++ b/src/controllers/users/fetch-user.ts @@ -1,22 +1,22 @@ -import user from 'services/users' -import type { Request, Response } from 'express' -import { badRequest } from 'helpers/http-errors' -import handleResponse from 'helpers/handle-response' +import user from "services/users"; +import type { Request, Response } from "express"; +import { badRequest } from "helpers/http-errors"; +import handleResponse from "helpers/handle-response"; async function userFetchUserController( req: Request, - res: Response, + res: Response ): Promise { - const id = res.locals.user.id + const id = res.locals.user.id; if (id === undefined) { - badRequest(res, 'Missing id') - return + badRequest(res, "Missing id"); + return; } - const result = await user.fetchUser(id) + const result = await user.fetchUser(id); - handleResponse(res, result) + handleResponse(res, result); } -export default userFetchUserController +export default userFetchUserController; diff --git a/src/controllers/users/follow-user.ts b/src/controllers/users/follow-user.ts index 42ebb31..0b1927d 100644 --- a/src/controllers/users/follow-user.ts +++ b/src/controllers/users/follow-user.ts @@ -1,17 +1,17 @@ -import user from 'services/users' -import type { Request, Response } from 'express' -import handleResponse from 'helpers/handle-response' +import user from "services/users"; +import type { Request, Response } from "express"; +import handleResponse from "helpers/handle-response"; async function userFollowController( req: Request, - res: Response, + res: Response ): Promise { - const userId = res.locals.user.id - const { userToFollow } = req.body + const userId = res.locals.user.id; + const { userToFollow } = req.body; - const result = await user.follow(userId, userToFollow) + const result = await user.follow(userId, userToFollow); - handleResponse(res, result) + handleResponse(res, result); } -export default userFollowController +export default userFollowController; diff --git a/src/controllers/users/index.ts b/src/controllers/users/index.ts index 7bf84c5..bf0fcde 100644 --- a/src/controllers/users/index.ts +++ b/src/controllers/users/index.ts @@ -1,17 +1,17 @@ -import userAuthController from './auth' -import userDeleteController from './delete' -import userFollowController from './follow-user' -import userFetchInfoController from './fetch-info' -import userFetchPostsController from './fetch-posts' -import userFetchUserController from './fetch-user' -import userLikeCommentController from './like-comment' -import userLikePostController from './like-post' -import userSearchController from './search-user' -import userSignupController from './signup' -import userUpdateEmailController from './update-email' -import userUpdateNameController from './update-name' -import userUpdatePasswordController from './update-password' -import userUploadPictureController from './upload-picture' +import userAuthController from "./auth"; +import userDeleteController from "./delete"; +import userFollowController from "./follow-user"; +import userFetchInfoController from "./fetch-info"; +import userFetchPostsController from "./fetch-posts"; +import userFetchUserController from "./fetch-user"; +import userLikeCommentController from "./like-comment"; +import userLikePostController from "./like-post"; +import userSearchController from "./search-user"; +import userSignupController from "./signup"; +import userUpdateEmailController from "./update-email"; +import userUpdateNameController from "./update-name"; +import userUpdatePasswordController from "./update-password"; +import userUploadPictureController from "./upload-picture"; const user = { auth: userAuthController, @@ -28,6 +28,6 @@ const user = { updateName: userUpdateNameController, updatePassword: userUpdatePasswordController, uploadPicture: userUploadPictureController, -} as const +} as const; -export default user +export default user; diff --git a/src/controllers/users/like-comment.ts b/src/controllers/users/like-comment.ts index 50aa65c..628c717 100644 --- a/src/controllers/users/like-comment.ts +++ b/src/controllers/users/like-comment.ts @@ -1,17 +1,17 @@ -import user from 'services/users' -import type { Request, Response } from 'express' -import handleResponse from 'helpers/handle-response' +import user from "services/users"; +import type { Request, Response } from "express"; +import handleResponse from "helpers/handle-response"; async function userLikeCommentController( req: Request, - res: Response, + res: Response ): Promise { - const userId = res.locals.user.id - const { commentId } = req.body + const userId = res.locals.user.id; + const { commentId } = req.body; - const result = await user.likeComment(commentId, userId) + const result = await user.likeComment(commentId, userId); - handleResponse(res, result) + handleResponse(res, result); } -export default userLikeCommentController +export default userLikeCommentController; diff --git a/src/controllers/users/like-post.ts b/src/controllers/users/like-post.ts index 288229b..96024a2 100644 --- a/src/controllers/users/like-post.ts +++ b/src/controllers/users/like-post.ts @@ -1,17 +1,17 @@ -import user from 'services/users' -import type { Request, Response } from 'express' -import handleResponse from 'helpers/handle-response' +import user from "services/users"; +import type { Request, Response } from "express"; +import handleResponse from "helpers/handle-response"; async function userLikePostController( req: Request, - res: Response, + res: Response ): Promise { - const userId = res.locals.user.id - const { postId } = req.body + const userId = res.locals.user.id; + const { postId } = req.body; - const result = await user.likePost(postId, userId) + const result = await user.likePost(postId, userId); - handleResponse(res, result) + handleResponse(res, result); } -export default userLikePostController +export default userLikePostController; diff --git a/src/controllers/users/search-user.ts b/src/controllers/users/search-user.ts index aac892c..9ab1a39 100644 --- a/src/controllers/users/search-user.ts +++ b/src/controllers/users/search-user.ts @@ -1,21 +1,21 @@ -import user from 'services/users' -import type { Request, Response } from 'express' -import { badRequest } from 'helpers/http-errors' +import user from "services/users"; +import type { Request, Response } from "express"; +import { badRequest } from "helpers/http-errors"; async function userSearchController( req: Request, - res: Response, + res: Response ): Promise { - const username = req.query.u as string + const username = req.query.u as string; if (username === undefined) { - badRequest(res, 'Missing username') - return + badRequest(res, "Missing username"); + return; } - const result = await user.searchUser(username) + const result = await user.searchUser(username); - res.json(result) + res.json(result); } -export default userSearchController +export default userSearchController; diff --git a/src/controllers/users/signup.ts b/src/controllers/users/signup.ts index 2daa090..70c05ef 100644 --- a/src/controllers/users/signup.ts +++ b/src/controllers/users/signup.ts @@ -1,16 +1,16 @@ -import user from 'services/users' -import type { Request, Response } from 'express' -import handleResponse from 'helpers/handle-response' +import user from "services/users"; +import type { Request, Response } from "express"; +import handleResponse from "helpers/handle-response"; async function userSignupController( req: Request, - res: Response, + res: Response ): Promise { - const { username, email, password } = req.body + const { username, email, password } = req.body; - const result = await user.signup({ username, email, password }) + const result = await user.signup({ username, email, password }); - handleResponse(res, result) + handleResponse(res, result); } -export default userSignupController +export default userSignupController; diff --git a/src/controllers/users/update-email.ts b/src/controllers/users/update-email.ts index 4fc30d2..d5047e4 100644 --- a/src/controllers/users/update-email.ts +++ b/src/controllers/users/update-email.ts @@ -1,17 +1,17 @@ -import user from 'services/users' -import type { Request, Response } from 'express' -import handleResponse from 'helpers/handle-response' +import user from "services/users"; +import type { Request, Response } from "express"; +import handleResponse from "helpers/handle-response"; async function userUpdateEmailController( req: Request, - res: Response, + res: Response ): Promise { - const { email } = req.body - const id = res.locals.user.id + const { email } = req.body; + const id = res.locals.user.id; - const result = await user.updateEmail({ id, email }) + const result = await user.updateEmail({ id, email }); - handleResponse(res, result) + handleResponse(res, result); } -export default userUpdateEmailController +export default userUpdateEmailController; diff --git a/src/controllers/users/update-name.ts b/src/controllers/users/update-name.ts index 160aaa9..89566f2 100644 --- a/src/controllers/users/update-name.ts +++ b/src/controllers/users/update-name.ts @@ -1,17 +1,17 @@ -import user from 'services/users' -import type { Request, Response } from 'express' -import handleResponse from 'helpers/handle-response' +import user from "services/users"; +import type { Request, Response } from "express"; +import handleResponse from "helpers/handle-response"; async function userUpdateNameController( req: Request, - res: Response, + res: Response ): Promise { - const { displayName, username } = req.body - const id = res.locals.user.id + const { displayName, username } = req.body; + const id = res.locals.user.id; - const result = await user.updateName({ id, displayName, username }) + const result = await user.updateName({ id, displayName, username }); - handleResponse(res, result) + handleResponse(res, result); } -export default userUpdateNameController +export default userUpdateNameController; diff --git a/src/controllers/users/update-password.ts b/src/controllers/users/update-password.ts index 9e8ce97..86e33a8 100644 --- a/src/controllers/users/update-password.ts +++ b/src/controllers/users/update-password.ts @@ -1,17 +1,17 @@ -import user from 'services/users' -import type { Request, Response } from 'express' -import handleResponse from 'helpers/handle-response' +import user from "services/users"; +import type { Request, Response } from "express"; +import handleResponse from "helpers/handle-response"; async function userUpdatePasswordController( req: Request, - res: Response, + res: Response ): Promise { - const { currentPassword, newPassword } = req.body - const id = res.locals.user.id + const { currentPassword, newPassword } = req.body; + const id = res.locals.user.id; - const result = await user.updatePassword(id, currentPassword, newPassword) + const result = await user.updatePassword(id, currentPassword, newPassword); - handleResponse(res, result) + handleResponse(res, result); } -export default userUpdatePasswordController +export default userUpdatePasswordController; diff --git a/src/controllers/users/upload-picture.ts b/src/controllers/users/upload-picture.ts index 40197fb..24c562d 100644 --- a/src/controllers/users/upload-picture.ts +++ b/src/controllers/users/upload-picture.ts @@ -1,33 +1,32 @@ -/* eslint-disable @typescript-eslint/restrict-template-expressions */ -import user from 'services/users' -import type { Request, Response } from 'express' -import { badRequest } from 'helpers/http-errors' -import handleResponse from 'helpers/handle-response' +import user from "services/users"; +import type { Request, Response } from "express"; +import { badRequest } from "helpers/http-errors"; +import handleResponse from "helpers/handle-response"; async function userUploadPictureController( req: Request, - res: Response, + res: Response ): Promise { if (req.file === undefined) { - badRequest(res, 'Expected a JPG or PNG file') - return + badRequest(res, "Expected a JPG or PNG file"); + return; } - const userId = res.locals.user.id + const userId = res.locals.user.id; - let url: string + let url: string; - if (process.env.NODE_ENV === 'development') { + if (process.env.NODE_ENV === "development") { url = `http://${ - process.env.AWS_BUCKET ?? '' - }.s3.localhost.localstack.cloud:4566/${req.file.key}` + process.env.AWS_BUCKET ?? "" + }.s3.localhost.localstack.cloud:4566/${req.file.key}`; } else { - url = req.file.location + url = req.file.location; } - const result = await user.uploadPicture(userId, url) + const result = await user.uploadPicture(userId, url); - handleResponse(res, result) + handleResponse(res, result); } -export default userUploadPictureController +export default userUploadPictureController; diff --git a/src/helpers/compress-image.ts b/src/helpers/compress-image.ts index 1a81551..a01a652 100644 --- a/src/helpers/compress-image.ts +++ b/src/helpers/compress-image.ts @@ -1,43 +1,42 @@ -import sharp from 'sharp' -import s3 from 'clients/s3-client' -import { GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3' +import sharp from "sharp"; +import s3 from "clients/s3-client"; +import { GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3"; export default async function compressImage( imageName: string, - isProfilePicture: string, + isProfilePicture: string ): Promise> { // Get file from s3 const { Body } = await s3.send( new GetObjectCommand({ - Bucket: process.env.AWS_BUCKET ?? '', + Bucket: process.env.AWS_BUCKET ?? "", Key: imageName, - }), - ) + }) + ); - const imageBuffer = await Body?.transformToByteArray() + const imageBuffer = await Body?.transformToByteArray(); const compressedImageBuffer = await sharp(imageBuffer) .resize( - isProfilePicture === 'true' ? 200 : undefined, - isProfilePicture === 'true' ? 200 : undefined, + isProfilePicture === "true" ? 200 : undefined, + isProfilePicture === "true" ? 200 : undefined ) .jpeg({ quality: 65 }) - .toBuffer() + .toBuffer(); // Send file back const params = { - Bucket: process.env.AWS_BUCKET ?? '', + Bucket: process.env.AWS_BUCKET ?? "", Key: imageName, Body: compressedImageBuffer, - ContentType: 'image/jpeg', - ContentDisposition: 'inline', - } + ContentType: "image/jpeg", + ContentDisposition: "inline", + }; - const { ETag } = await s3.send(new PutObjectCommand(params)) + const { ETag } = await s3.send(new PutObjectCommand(params)); if (ETag !== null) { - return {} - } else { - return new Error('Error while compressing image') + return {}; } + return new Error("Error while compressing image"); } diff --git a/src/helpers/handle-response.ts b/src/helpers/handle-response.ts index c62e7ba..0b6d567 100644 --- a/src/helpers/handle-response.ts +++ b/src/helpers/handle-response.ts @@ -1,10 +1,11 @@ -import { type Response } from 'express' -import { badRequest } from './http-errors' +import { type Response } from "express"; +import { badRequest } from "./http-errors"; +// biome-ignore lint/suspicious/noExplicitAny: don't question it. export default function handleResponse(res: Response, result: any): void { if (result instanceof Error) { - badRequest(res, result.message) + badRequest(res, result.message); } else { - res.json(result) + res.json(result); } } diff --git a/src/helpers/http-errors.ts b/src/helpers/http-errors.ts index 0b7c54e..af1b8f4 100644 --- a/src/helpers/http-errors.ts +++ b/src/helpers/http-errors.ts @@ -1,28 +1,28 @@ -import { type Response } from 'express' +import { type Response } from "express"; const sendErrorResponse = ( res: Response, status: number, - message: string, + message: string ): void => { - res.status(status).json({ error: message }) -} + res.status(status).json({ error: message }); +}; -export const badRequest = (res: Response, message = 'Bad Request'): void => { - sendErrorResponse(res, 400, message) -} +export const badRequest = (res: Response, message = "Bad Request"): void => { + sendErrorResponse(res, 400, message); +}; -export const unauthorized = (res: Response, message = 'Unauthorized'): void => { - sendErrorResponse(res, 401, message) -} +export const unauthorized = (res: Response, message = "Unauthorized"): void => { + sendErrorResponse(res, 401, message); +}; -export const forbidden = (res: Response, message = 'Forbidden'): void => { - sendErrorResponse(res, 403, message) -} +export const forbidden = (res: Response, message = "Forbidden"): void => { + sendErrorResponse(res, 403, message); +}; export const internalServerError = ( res: Response, - message = 'Internal Server Error', + message = "Internal Server Error" ): void => { - sendErrorResponse(res, 500, message) -} + sendErrorResponse(res, 500, message); +}; diff --git a/src/helpers/logger.ts b/src/helpers/logger.ts index a77dcf2..c711d91 100644 --- a/src/helpers/logger.ts +++ b/src/helpers/logger.ts @@ -1,4 +1,4 @@ -import winston from 'winston' +import winston from "winston"; const levels = { error: 0, @@ -6,47 +6,45 @@ const levels = { info: 2, http: 3, debug: 4, -} +}; const level = (): string => { - // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions, @typescript-eslint/prefer-nullish-coalescing - const env = process.env.NODE_ENV || 'development' - const isDevelopment = env === 'development' - return isDevelopment ? 'debug' : 'warn' -} + const env = process.env.NODE_ENV || "development"; + const isDevelopment = env === "development"; + return isDevelopment ? "debug" : "warn"; +}; const colors = { - error: 'red', - warn: 'yellow', - info: 'green', - http: 'magenta', - debug: 'white', -} + error: "red", + warn: "yellow", + info: "green", + http: "magenta", + debug: "white", +}; -winston.addColors(colors) +winston.addColors(colors); const format = winston.format.combine( - winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss:ms' }), + winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss:ms" }), winston.format.colorize({ all: true }), winston.format.printf( - // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - info => `${info.timestamp} ${info.level}: ${info.message}`, - ), -) + (info) => `${info.timestamp} ${info.level}: ${info.message}` + ) +); const transports = [ new winston.transports.Console(), new winston.transports.File({ - filename: 'logs/error.log', - level: 'error', + filename: "logs/error.log", + level: "error", }), -] +]; const logger = winston.createLogger({ level: level(), levels, format, transports, -}) +}); -export default logger +export default logger; diff --git a/src/helpers/notification.ts b/src/helpers/notification.ts index ba79658..c285b51 100644 --- a/src/helpers/notification.ts +++ b/src/helpers/notification.ts @@ -1,11 +1,11 @@ -import { type NotificationType } from '@prisma/client' -import prisma from 'clients/prisma-client' +import { type NotificationType } from "@prisma/client"; +import prisma from "clients/prisma-client"; export async function createNotification( fromUserId: string, toUserId: string, content: string, - type: NotificationType, + type: NotificationType ): Promise | Error> { try { await prisma.notifications.create({ @@ -25,25 +25,25 @@ export async function createNotification( }, }, }, - }) - return {} + }); + return {}; } catch (_) { - return new Error('Error while creating notification') + return new Error("Error while creating notification"); } } export async function countNotifications( - toUserId: string, + toUserId: string ): Promise { try { const count = await prisma.notifications.count({ where: { toUserId, }, - }) + }); - return count + return count; } catch (_) { - return new Error('Error while counting user notifications') + return new Error("Error while counting user notifications"); } } diff --git a/src/helpers/parse-swagger.ts b/src/helpers/parse-swagger.ts index 26111e8..c3f30b2 100644 --- a/src/helpers/parse-swagger.ts +++ b/src/helpers/parse-swagger.ts @@ -1,7 +1,7 @@ -import { parse } from 'yaml' -import { readFileSync } from 'fs' +import { parse } from "yaml"; +import { readFileSync } from "fs"; -const swaggerConfigFile = readFileSync('./swagger.yaml', 'utf-8') -const swaggerDocument = parse(swaggerConfigFile) +const swaggerConfigFile = readFileSync("./swagger.yaml", "utf-8"); +const swaggerDocument = parse(swaggerConfigFile); -export default swaggerDocument +export default swaggerDocument; diff --git a/src/interfaces/jwt.ts b/src/interfaces/jwt.ts index a847ad3..3328c41 100644 --- a/src/interfaces/jwt.ts +++ b/src/interfaces/jwt.ts @@ -1,7 +1,7 @@ interface jwtPayload { - id: string - iat: number - exp: number + id: string; + iat: number; + exp: number; } -export default jwtPayload +export default jwtPayload; diff --git a/src/interfaces/user.ts b/src/interfaces/user.ts index f22dbac..4f67220 100644 --- a/src/interfaces/user.ts +++ b/src/interfaces/user.ts @@ -1,13 +1,13 @@ interface User { - id?: string - displayName?: string | null - username?: string - email?: string - password?: string - profileImage?: string | null - createdAt?: Date - token?: string - socketId?: string + id?: string; + displayName?: string | null; + username?: string; + email?: string; + password?: string; + profileImage?: string | null; + createdAt?: Date; + token?: string; + socketId?: string; } -export default User +export default User; diff --git a/src/middlewares/authenticated.ts b/src/middlewares/authenticated.ts index 671d702..338f369 100644 --- a/src/middlewares/authenticated.ts +++ b/src/middlewares/authenticated.ts @@ -1,56 +1,56 @@ -import { verify } from 'jsonwebtoken' -import prisma from 'clients/prisma-client' -import type { Response, Request, NextFunction } from 'express' -import { unauthorized } from 'helpers/http-errors' -import type jwtPayload from 'interfaces/jwt' +import { verify } from "jsonwebtoken"; +import prisma from "clients/prisma-client"; +import type { Response, Request, NextFunction } from "express"; +import { unauthorized } from "helpers/http-errors"; +import type jwtPayload from "interfaces/jwt"; async function authenticated( req: Request, res: Response, - next: NextFunction, + next: NextFunction ): Promise { try { if ( req.headers.authorization === undefined || req.headers.authorization.length === 0 ) { - unauthorized(res, 'Missing token') - return + unauthorized(res, "Missing token"); + return; } - const token = req.headers.authorization.split(' ')[1] + const token = req.headers.authorization.split(" ")[1]; if (token === undefined) { - unauthorized(res, 'Missing token') - return + unauthorized(res, "Missing token"); + return; } const { id } = verify( token, - process.env.JWT_ACCESS_SECRET ?? '', - ) as jwtPayload + process.env.JWT_ACCESS_SECRET ?? "" + ) as jwtPayload; if (id === undefined) { - unauthorized(res, 'Invalid token') - return + unauthorized(res, "Invalid token"); + return; } const user = await prisma.user.findFirst({ where: { id, }, - }) + }); if (user === undefined) { - unauthorized(res, 'User does not exists') - return + unauthorized(res, "User does not exists"); + return; } - res.locals.user = user - next() + res.locals.user = user; + next(); } catch (e) { - unauthorized(res, `JWT Error: ${(e as Error).message}`) + unauthorized(res, `JWT Error: ${(e as Error).message}`); } } -export default authenticated +export default authenticated; diff --git a/src/middlewares/morgan.ts b/src/middlewares/morgan.ts index bf42475..d3f9a5b 100644 --- a/src/middlewares/morgan.ts +++ b/src/middlewares/morgan.ts @@ -1,12 +1,12 @@ -import morgan, { type StreamOptions } from 'morgan' -import logger from 'helpers/logger' +import morgan, { type StreamOptions } from "morgan"; +import logger from "helpers/logger"; const stream: StreamOptions = { - write: message => logger.http(message), -} + write: (message) => logger.http(message), +}; -const morganMiddleware = morgan(':method :url :status - :response-time ms', { +const morganMiddleware = morgan(":method :url :status - :response-time ms", { stream, -}) +}); -export default morganMiddleware +export default morganMiddleware; diff --git a/src/middlewares/rate-limit.ts b/src/middlewares/rate-limit.ts index f6be82f..aae38a4 100644 --- a/src/middlewares/rate-limit.ts +++ b/src/middlewares/rate-limit.ts @@ -1,26 +1,26 @@ -import rateLimit from 'express-rate-limit' -import RedisStore from 'rate-limit-redis' -import redis from 'clients/redis-client' -import logger from 'helpers/logger' +import rateLimit from "express-rate-limit"; +import RedisStore from "rate-limit-redis"; +import redis from "clients/redis-client"; +import logger from "helpers/logger"; -let skip: boolean +let skip: boolean; -if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') { - logger.info('Development environment detected. Rate limit is now disabled.') - skip = true +if (process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") { + logger.info("Development environment detected. Rate limit is now disabled."); + skip = true; } else { - skip = false + skip = false; } const limiter = rateLimit({ windowMs: 1 * 60 * 1000, // 60 seconds max: 5, - message: { error: 'Too many requests' }, + message: { error: "Too many requests" }, legacyHeaders: false, skip: (_req, _res) => skip, store: new RedisStore({ sendCommand: async (...args: string[]) => await redis.sendCommand(args), }), -}) +}); -export default limiter +export default limiter; diff --git a/src/middlewares/upload-image.ts b/src/middlewares/upload-image.ts index 9431877..814c213 100644 --- a/src/middlewares/upload-image.ts +++ b/src/middlewares/upload-image.ts @@ -1,32 +1,33 @@ -import type { Response, Request, NextFunction } from 'express' -import multer from 'multer' -import multerConfig from 'config/multer' -import compressImage from 'helpers/compress-image' -import { badRequest } from 'helpers/http-errors' +import type { Response, Request, NextFunction } from "express"; +import multer from "multer"; +import multerConfig from "config/multer"; +import compressImage from "helpers/compress-image"; +import { badRequest } from "helpers/http-errors"; function uploadImage(req: Request, res: Response, next: NextFunction): void { - const upload = multer(multerConfig).single('image') + const upload = multer(multerConfig).single("image"); + // biome-ignore lint/suspicious/noExplicitAny: i don't know, it's working, no need to change anything here. upload(req, res, async (cb: multer.MulterError | Error | any) => { if (req.res?.locals.user == null) { - badRequest(res, 'You must be logged in to upload a profile picture') - return + badRequest(res, "You must be logged in to upload a profile picture"); + return; } if (cb instanceof multer.MulterError || cb instanceof Error) { - badRequest(res, cb.message) - return + badRequest(res, cb.message); + return; } if (req.file === undefined) { - badRequest(res, 'Expected file') - return + badRequest(res, "Expected file"); + return; } - await compressImage(req.file?.key, req.body.isProfilePicture) + await compressImage(req.file?.key, req.body.isProfilePicture); - next() - }) + next(); + }); } -export default uploadImage +export default uploadImage; diff --git a/src/routes.ts b/src/routes.ts index 4a4f5c6..3e56cbf 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -1,14 +1,14 @@ -import { Router } from 'express' +import { Router } from "express"; // Routers -import usersRouter from 'controllers/users-router' -import postsRouter from 'controllers/posts-router' -import commentsRouter from 'controllers/comments-router' +import usersRouter from "controllers/users-router"; +import postsRouter from "controllers/posts-router"; +import commentsRouter from "controllers/comments-router"; -const router = Router() +const router = Router(); -router.use('/user', usersRouter) -router.use('/post', postsRouter) -router.use('/comment', commentsRouter) +router.use("/user", usersRouter); +router.use("/post", postsRouter); +router.use("/comment", commentsRouter); -export default router +export default router; diff --git a/src/server.ts b/src/server.ts index 60ef14a..2e5880c 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1,26 +1,19 @@ -import app from './app' -import { createServer } from 'http' -import logger from 'helpers/logger' -import createSocketIOInstance from './socket' +import app from "./app"; +import { createServer } from "http"; +import logger from "helpers/logger"; -import prisma from 'clients/prisma-client' -import redis from 'clients/redis-client' +import prisma from "clients/prisma-client"; +import redis from "clients/redis-client"; -const server = createServer(app) -const io = createSocketIOInstance(server) - -app.use((req, res, next) => { - res.locals.io = io - next() -}) +const server = createServer(app); server.listen(process.env.SERVER_PORT, () => { - logger.info(`Server is running @ ${process.env.SERVER_PORT ?? ''}`) -}) + logger.info(`Server is running @ ${process.env.SERVER_PORT ?? ""}`); +}); -process.on('SIGINT', async () => { - logger.warn('Closing server...') - await prisma.$disconnect() - await redis.disconnect() - server.close() -}) +process.on("SIGINT", async () => { + logger.warn("Closing server..."); + await prisma.$disconnect(); + await redis.disconnect(); + server.close(); +}); diff --git a/src/services/comments/create.ts b/src/services/comments/create.ts index 11577b7..decae63 100644 --- a/src/services/comments/create.ts +++ b/src/services/comments/create.ts @@ -1,28 +1,28 @@ -import prisma from 'clients/prisma-client' +import prisma from "clients/prisma-client"; async function commentCreateService( postId: string, content: string, - authorId: string, + authorId: string ): Promise | Error> { const post = await prisma.post.findFirst({ where: { id: postId, }, - }) + }); if (post === null) { - return new Error('Post not found') + return new Error("Post not found"); } const user = await prisma.user.findFirst({ where: { id: authorId, }, - }) + }); if (user === null) { - return new Error('User not found') + return new Error("User not found"); } const comment = await prisma.comments.create({ @@ -31,9 +31,9 @@ async function commentCreateService( postId, userId: authorId, }, - }) + }); - return comment + return comment; } -export default commentCreateService +export default commentCreateService; diff --git a/src/services/comments/delete.ts b/src/services/comments/delete.ts index 4f0965b..9fba6f4 100644 --- a/src/services/comments/delete.ts +++ b/src/services/comments/delete.ts @@ -1,17 +1,17 @@ -import prisma from 'clients/prisma-client' +import prisma from "clients/prisma-client"; async function commentDeleteService( commentId: string, - authorId: string, + authorId: string ): Promise | Error> { const user = await prisma.user.findFirst({ where: { id: authorId, }, - }) + }); if (user === null) { - return new Error('User not found') + return new Error("User not found"); } const comment = await prisma.comments.findFirst({ @@ -19,10 +19,10 @@ async function commentDeleteService( id: commentId, userId: user.id, }, - }) + }); if (comment === null) { - return new Error('Comment not found') + return new Error("Comment not found"); } await prisma.comments.deleteMany({ @@ -30,9 +30,9 @@ async function commentDeleteService( id: comment.id, userId: user.id, }, - }) + }); - return {} + return {}; } -export default commentDeleteService +export default commentDeleteService; diff --git a/src/services/comments/fetch-info.ts b/src/services/comments/fetch-info.ts index 6c52ec1..61d2ad7 100644 --- a/src/services/comments/fetch-info.ts +++ b/src/services/comments/fetch-info.ts @@ -1,7 +1,7 @@ -import prisma from 'clients/prisma-client' +import prisma from "clients/prisma-client"; async function commentFetchService( - commentId: string, + commentId: string ): Promise | Error> { const comment = await prisma.comments.findFirst({ where: { @@ -21,13 +21,13 @@ async function commentFetchService( }, }, }, - }) + }); if (comment === null) { - return new Error('Comment not found') + return new Error("Comment not found"); } - return comment + return comment; } -export default commentFetchService +export default commentFetchService; diff --git a/src/services/comments/fetch-likes.ts b/src/services/comments/fetch-likes.ts index 3cb151f..7949824 100644 --- a/src/services/comments/fetch-likes.ts +++ b/src/services/comments/fetch-likes.ts @@ -1,4 +1,4 @@ -import prisma from 'clients/prisma-client' +import prisma from "clients/prisma-client"; async function commentFetchLikesService(id: string): Promise { const post = await prisma.commentLike.findMany({ @@ -14,13 +14,13 @@ async function commentFetchLikesService(id: string): Promise { }, }, }, - }) + }); if (post === null) { - return new Error('Comment not found') + return new Error("Comment not found"); } - return post + return post; } -export default commentFetchLikesService +export default commentFetchLikesService; diff --git a/src/services/comments/index.ts b/src/services/comments/index.ts index a4728bb..85ec0bb 100644 --- a/src/services/comments/index.ts +++ b/src/services/comments/index.ts @@ -1,8 +1,8 @@ -import commentCreateService from './create' -import commentDeleteService from './delete' -import commentFetchService from './fetch-info' -import commentFetchLikesService from './fetch-likes' -import commentUpdateService from './update' +import commentCreateService from "./create"; +import commentDeleteService from "./delete"; +import commentFetchService from "./fetch-info"; +import commentFetchLikesService from "./fetch-likes"; +import commentUpdateService from "./update"; const comment = { create: commentCreateService, @@ -10,6 +10,6 @@ const comment = { fetch: commentFetchService, fetchLikes: commentFetchLikesService, update: commentUpdateService, -} as const +} as const; -export default comment +export default comment; diff --git a/src/services/comments/update.ts b/src/services/comments/update.ts index 7809797..88d3d59 100644 --- a/src/services/comments/update.ts +++ b/src/services/comments/update.ts @@ -1,19 +1,19 @@ -import prisma from 'clients/prisma-client' +import prisma from "clients/prisma-client"; async function commentUpdateService( content: string, authorId: string, - commentId: string, + commentId: string ): Promise | Error> { const comment = await prisma.comments.findFirst({ where: { id: commentId, userId: authorId, }, - }) + }); if (comment === null) { - return new Error('Comment does not exists') + return new Error("Comment does not exists"); } const updatedComment = await prisma.comments.update({ @@ -37,8 +37,8 @@ async function commentUpdateService( }, }, }, - }) - return updatedComment + }); + return updatedComment; } -export default commentUpdateService +export default commentUpdateService; diff --git a/src/services/posts/create.ts b/src/services/posts/create.ts index ae1c024..fd11a68 100644 --- a/src/services/posts/create.ts +++ b/src/services/posts/create.ts @@ -1,13 +1,13 @@ -import prisma from 'clients/prisma-client' +import prisma from "clients/prisma-client"; async function postCreateService( content: string, - authorId: string, + authorId: string ): Promise | Error> { - const user = await prisma.user.findFirst({ where: { id: authorId } }) + const user = await prisma.user.findFirst({ where: { id: authorId } }); if (user === null) { - return new Error("This user doesn't exists") + return new Error("This user doesn't exists"); } const post = await prisma.post.create({ @@ -15,9 +15,9 @@ async function postCreateService( content, authorId, }, - }) + }); - return post + return post; } -export default postCreateService +export default postCreateService; diff --git a/src/services/posts/delete.ts b/src/services/posts/delete.ts index 8738701..bf9673f 100644 --- a/src/services/posts/delete.ts +++ b/src/services/posts/delete.ts @@ -1,30 +1,30 @@ -import prisma from 'clients/prisma-client' +import prisma from "clients/prisma-client"; async function postDeleteService( postId: string, - userId: string, + userId: string ): Promise | Error> { - const post = await prisma.post.findFirst({ where: { id: postId } }) + const post = await prisma.post.findFirst({ where: { id: postId } }); if (post === null) { - return new Error('Post not found') + return new Error("Post not found"); } if ((await prisma.user.findFirst({ where: { id: userId } })) === null) { - return new Error('User not found') + return new Error("User not found"); } if (post.authorId !== userId) { - return new Error('Forbidden') + return new Error("Forbidden"); } await prisma.post.deleteMany({ where: { id: postId, }, - }) + }); - return {} + return {}; } -export default postDeleteService +export default postDeleteService; diff --git a/src/services/posts/fetch-info.ts b/src/services/posts/fetch-info.ts index e0cd61b..2383ba4 100644 --- a/src/services/posts/fetch-info.ts +++ b/src/services/posts/fetch-info.ts @@ -1,7 +1,7 @@ -import prisma from 'clients/prisma-client' +import prisma from "clients/prisma-client"; async function postFetchInfoService( - id: string, + id: string ): Promise | Error> { const post = await prisma.post.findFirst({ where: { @@ -21,13 +21,13 @@ async function postFetchInfoService( }, }, }, - }) + }); if (post === null) { - return new Error('Post not found') + return new Error("Post not found"); } - return post + return post; } -export default postFetchInfoService +export default postFetchInfoService; diff --git a/src/services/posts/fetch-likes.ts b/src/services/posts/fetch-likes.ts index e32f295..a7f2210 100644 --- a/src/services/posts/fetch-likes.ts +++ b/src/services/posts/fetch-likes.ts @@ -1,4 +1,4 @@ -import prisma from 'clients/prisma-client' +import prisma from "clients/prisma-client"; async function postFetchLikesService(id: string): Promise { const post = await prisma.postLike.findMany({ @@ -14,13 +14,13 @@ async function postFetchLikesService(id: string): Promise { }, }, }, - }) + }); if (post === null) { - return new Error('Post not found') + return new Error("Post not found"); } - return post + return post; } -export default postFetchLikesService +export default postFetchLikesService; diff --git a/src/services/posts/index.ts b/src/services/posts/index.ts index 86f2883..2fc65de 100644 --- a/src/services/posts/index.ts +++ b/src/services/posts/index.ts @@ -1,8 +1,8 @@ -import postCreateService from './create' -import postDeleteService from './delete' -import postFetchInfoService from './fetch-info' -import postFetchLikesService from './fetch-likes' -import postUpdateService from './update' +import postCreateService from "./create"; +import postDeleteService from "./delete"; +import postFetchInfoService from "./fetch-info"; +import postFetchLikesService from "./fetch-likes"; +import postUpdateService from "./update"; const post = { create: postCreateService, @@ -10,6 +10,6 @@ const post = { fetch: postFetchInfoService, fetchLikes: postFetchLikesService, update: postUpdateService, -} as const +} as const; -export default post +export default post; diff --git a/src/services/posts/update.ts b/src/services/posts/update.ts index b694e2c..fa8708e 100644 --- a/src/services/posts/update.ts +++ b/src/services/posts/update.ts @@ -1,26 +1,27 @@ -import prisma from 'clients/prisma-client' +import prisma from "clients/prisma-client"; async function postUpdateService( postId: string, content: string, - userId: string, + userId: string ): Promise | Error> { - const post = await prisma.post.findFirst({ where: { id: postId } }) + const post = await prisma.post.findFirst({ where: { id: postId } }); if (post === null) { - return new Error('Post not found') + return new Error("Post not found"); } if ((await prisma.user.findFirst({ where: { id: userId } })) === null) { - return new Error('User not found') + return new Error("User not found"); } if (post.authorId !== userId) { - return new Error('Forbidden') + return new Error("Forbidden"); } if (post.content === content.trim()) { - content = post.content + let postContent: string = content; + postContent = post.content; } const updatedPost = await prisma.post.update({ @@ -42,8 +43,8 @@ async function postUpdateService( }, }, }, - }) + }); - return updatedPost + return updatedPost; } -export default postUpdateService +export default postUpdateService; diff --git a/src/services/users/auth.ts b/src/services/users/auth.ts index 218662c..c733194 100644 --- a/src/services/users/auth.ts +++ b/src/services/users/auth.ts @@ -1,7 +1,7 @@ -import * as bcrypt from 'bcrypt' -import jsonwebtoken from 'jsonwebtoken' -import prisma from 'clients/prisma-client' -import type User from 'interfaces/user' +import * as bcrypt from "bcrypt"; +import jsonwebtoken from "jsonwebtoken"; +import prisma from "clients/prisma-client"; +import type User from "interfaces/user"; async function userAuthService({ email, @@ -11,37 +11,37 @@ async function userAuthService({ where: { email, }, - }) + }); if (user == null) { - return new Error('Invalid email or password') + return new Error("Invalid email or password"); } if (email === undefined || password === undefined) { - return new Error('Missing fields') + return new Error("Missing fields"); } const validPassword = await bcrypt.compare( - password.replace(/ /g, ''), - user.password, - ) + password.replace(/ /g, ""), + user.password + ); 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' }, - ) + process.env.JWT_ACCESS_SECRET ?? "", + { expiresIn: "1d" } + ); return { token: bearer, user: user.username, - } + }; } -export default userAuthService +export default userAuthService; diff --git a/src/services/users/delete.ts b/src/services/users/delete.ts index c872dba..6334b71 100644 --- a/src/services/users/delete.ts +++ b/src/services/users/delete.ts @@ -1,25 +1,25 @@ -import prisma from 'clients/prisma-client' +import prisma from "clients/prisma-client"; async function userDeleteService( - userId: string, + userId: string ): Promise | Error> { - const user = await prisma.user.findFirst({ where: { id: userId } }) + const user = await prisma.user.findFirst({ where: { id: userId } }); if (user === null) { - return new Error('User not found') + return new Error("User not found"); } if (user.id !== userId) { - return new Error('Forbidden') + return new Error("Forbidden"); } await prisma.user.deleteMany({ where: { id: userId, }, - }) + }); - return {} + return {}; } -export default userDeleteService +export default userDeleteService; diff --git a/src/services/users/fetch-info.ts b/src/services/users/fetch-info.ts index fb62477..b16e57b 100644 --- a/src/services/users/fetch-info.ts +++ b/src/services/users/fetch-info.ts @@ -1,7 +1,7 @@ -import prisma from 'clients/prisma-client' +import prisma from "clients/prisma-client"; async function userFetchInfoService( - username: string, + username: string ): Promise | Error> { const user = await prisma.user.findFirst({ where: { @@ -29,22 +29,22 @@ async function userFetchInfoService( }, }, }, - }) + }); if (user === null) { - return new Error('User not found') + return new Error("User not found"); } - const followers = user.followers.length - const following = user.following.length + const followers = user.followers.length; + const following = user.following.length; const info = { ...user, followers, following, - } + }; - return info + return info; } -export default userFetchInfoService +export default userFetchInfoService; diff --git a/src/services/users/fetch-posts.ts b/src/services/users/fetch-posts.ts index 4c0ab99..920b2aa 100644 --- a/src/services/users/fetch-posts.ts +++ b/src/services/users/fetch-posts.ts @@ -1,7 +1,7 @@ -import prisma from 'clients/prisma-client' +import prisma from "clients/prisma-client"; async function userFetchPostsService( - username: string, + username: string ): Promise { const posts = await prisma.post.findMany({ where: { @@ -23,8 +23,8 @@ async function userFetchPostsService( }, }, }, - }) - return posts + }); + return posts; } -export default userFetchPostsService +export default userFetchPostsService; diff --git a/src/services/users/fetch-user.ts b/src/services/users/fetch-user.ts index 966e00f..aaeff97 100644 --- a/src/services/users/fetch-user.ts +++ b/src/services/users/fetch-user.ts @@ -1,7 +1,7 @@ -import prisma from 'clients/prisma-client' +import prisma from "clients/prisma-client"; async function userFetchUserService( - id: string, + id: string ): Promise | Error> { const user = await prisma.user.findFirst({ where: { @@ -29,22 +29,22 @@ async function userFetchUserService( }, }, }, - }) + }); if (user === null) { - return new Error('User not found') + return new Error("User not found"); } - const followers = user.followers.length - const following = user.following.length + const followers = user.followers.length; + const following = user.following.length; const info = { ...user, followers, following, - } + }; - return info + return info; } -export default userFetchUserService +export default userFetchUserService; diff --git a/src/services/users/follow-user.ts b/src/services/users/follow-user.ts index 365ee4c..991f914 100644 --- a/src/services/users/follow-user.ts +++ b/src/services/users/follow-user.ts @@ -1,31 +1,31 @@ -import prisma from 'clients/prisma-client' +import prisma from "clients/prisma-client"; async function userFollowService( userId: string, - followingUsername: string, + followingUsername: string ): Promise | Error> { if (userId === undefined || followingUsername === undefined) { - return new Error('Missing fields') + return new Error("Missing fields"); } const user = await prisma.user.findFirst({ where: { username: followingUsername, }, - }) + }); if (user === null) { - return new Error('User not found') + return new Error("User not found"); } const userToFollow = await prisma.user.findFirst({ where: { id: userId, }, - }) + }); if (userToFollow === null) { - return new Error('User to follow not found') + return new Error("User to follow not found"); } const alreadyFollow = await prisma.follows.findFirst({ @@ -33,7 +33,7 @@ async function userFollowService( followerId: user.id, followingId: userToFollow.id, }, - }) + }); if (alreadyFollow !== null) { await prisma.follows.deleteMany({ @@ -41,8 +41,8 @@ async function userFollowService( followerId: user.id, followingId: userToFollow.id, }, - }) - return {} + }); + return {}; } const follow = await prisma.follows.create({ @@ -50,9 +50,9 @@ async function userFollowService( followerId: user.id, followingId: userToFollow.id, }, - }) + }); - return follow + return follow; } -export default userFollowService +export default userFollowService; diff --git a/src/services/users/index.ts b/src/services/users/index.ts index 1c921f9..b7f3795 100644 --- a/src/services/users/index.ts +++ b/src/services/users/index.ts @@ -1,17 +1,17 @@ -import userAuthService from './auth' -import userDeleteService from './delete' -import userFollowService from './follow-user' -import userFetchPostsService from './fetch-posts' -import userFetchInfoService from './fetch-info' -import userFetchUserService from './fetch-user' -import userLikeCommentService from './like-comment' -import userLikePostService from './like-post' -import userSearchService from './search-user' -import userSignupService from './signup' -import userUpdateEmailService from './update-email' -import userUpdateNameService from './update-name' -import userUpdatePasswordService from './update-password' -import userUploadPictureService from './upload-picture' +import userAuthService from "./auth"; +import userDeleteService from "./delete"; +import userFollowService from "./follow-user"; +import userFetchPostsService from "./fetch-posts"; +import userFetchInfoService from "./fetch-info"; +import userFetchUserService from "./fetch-user"; +import userLikeCommentService from "./like-comment"; +import userLikePostService from "./like-post"; +import userSearchService from "./search-user"; +import userSignupService from "./signup"; +import userUpdateEmailService from "./update-email"; +import userUpdateNameService from "./update-name"; +import userUpdatePasswordService from "./update-password"; +import userUploadPictureService from "./upload-picture"; const user = { auth: userAuthService, @@ -28,6 +28,6 @@ const user = { updateName: userUpdateNameService, updatePassword: userUpdatePasswordService, uploadPicture: userUploadPictureService, -} as const +} as const; -export default user +export default user; diff --git a/src/services/users/like-comment.ts b/src/services/users/like-comment.ts index d8617c8..3dd9bc8 100644 --- a/src/services/users/like-comment.ts +++ b/src/services/users/like-comment.ts @@ -1,31 +1,31 @@ -import prisma from 'clients/prisma-client' +import prisma from "clients/prisma-client"; async function userLikeCommentService( commentId: string, - userId: string, + userId: string ): Promise | Error> { if (commentId === undefined || userId === undefined) { - return new Error('Missing fields') + return new Error("Missing fields"); } const comment = await prisma.comments.findFirst({ where: { id: commentId, }, - }) + }); if (comment === null) { - return new Error('Comment not found') + return new Error("Comment not found"); } const user = await prisma.user.findFirst({ where: { id: userId, }, - }) + }); if (user === null) { - return new Error('User not found') + return new Error("User not found"); } const alreadyLiked = await prisma.commentLike.findFirst({ @@ -33,7 +33,7 @@ async function userLikeCommentService( commentId: comment.id, userId: user.id, }, - }) + }); if (alreadyLiked !== null) { await prisma.commentLike.deleteMany({ @@ -41,8 +41,8 @@ async function userLikeCommentService( commentId: comment.id, userId: user.id, }, - }) - return {} + }); + return {}; } const like = await prisma.commentLike.create({ @@ -50,9 +50,9 @@ async function userLikeCommentService( commentId: comment.id, userId: user.id, }, - }) + }); - return like + return like; } -export default userLikeCommentService +export default userLikeCommentService; diff --git a/src/services/users/like-post.ts b/src/services/users/like-post.ts index ac0d34c..b5e2d11 100644 --- a/src/services/users/like-post.ts +++ b/src/services/users/like-post.ts @@ -1,31 +1,31 @@ -import prisma from 'clients/prisma-client' +import prisma from "clients/prisma-client"; async function userLikePostService( postId: string, - userId: string, + userId: string ): Promise | Error> { if (postId === undefined || userId === undefined) { - return new Error('Missing fields') + return new Error("Missing fields"); } const post = await prisma.post.findFirst({ where: { id: postId, }, - }) + }); if (post === null) { - return new Error('Post not found') + return new Error("Post not found"); } const user = await prisma.user.findFirst({ where: { id: userId, }, - }) + }); if (user === null) { - return new Error('User not found') + return new Error("User not found"); } const alreadyLiked = await prisma.postLike.findFirst({ @@ -33,7 +33,7 @@ async function userLikePostService( postId: post.id, userId: user.id, }, - }) + }); if (alreadyLiked !== null) { await prisma.postLike.deleteMany({ @@ -41,8 +41,8 @@ async function userLikePostService( postId: post.id, userId: user.id, }, - }) - return {} + }); + return {}; } const like = await prisma.postLike.create({ @@ -50,9 +50,9 @@ async function userLikePostService( postId: post.id, userId: user.id, }, - }) + }); - return like + return like; } -export default userLikePostService +export default userLikePostService; diff --git a/src/services/users/search-user.ts b/src/services/users/search-user.ts index 2447c22..730e7d3 100644 --- a/src/services/users/search-user.ts +++ b/src/services/users/search-user.ts @@ -1,4 +1,4 @@ -import prisma from 'clients/prisma-client' +import prisma from "clients/prisma-client"; async function userSearchService(username: string): Promise { const users = await prisma.user.findMany({ @@ -13,8 +13,8 @@ async function userSearchService(username: string): Promise { profileImage: true, }, take: 10, - }) - return users + }); + return users; } -export default userSearchService +export default userSearchService; diff --git a/src/services/users/signup.ts b/src/services/users/signup.ts index e9248ba..4b4c9d3 100644 --- a/src/services/users/signup.ts +++ b/src/services/users/signup.ts @@ -1,10 +1,10 @@ -import * as bcrypt from 'bcrypt' -import validator from 'validator' -import prisma from 'clients/prisma-client' -import type User from 'interfaces/user' +import * as bcrypt from "bcrypt"; +import validator from "validator"; +import prisma from "clients/prisma-client"; +import type User from "interfaces/user"; -const passwordRegex = /^(?=.*[0-9])(?=.*[!@#$%^&*_])[a-zA-Z0-9!@#$%^&*_]{8,}$/ -const usernameRegex = /^[a-zA-Z0-9_.]{5,15}$/ +const passwordRegex = /^(?=.*[0-9])(?=.*[!@#$%^&*_])[a-zA-Z0-9!@#$%^&*_]{8,}$/; +const usernameRegex = /^[a-zA-Z0-9_.]{5,15}$/; async function userSignupService({ username, @@ -12,35 +12,35 @@ async function userSignupService({ password, }: User): Promise | Error> { if (username === undefined || email === undefined || password === undefined) { - return new Error('Missing fields') + return new Error("Missing fields"); } if (!passwordRegex.test(password)) { return new Error( - 'Password must have at least 8 characters, one number and one special character.', - ) + "Password must have at least 8 characters, one number and one special character." + ); } if (!usernameRegex.test(username)) { return new Error( - 'Username not allowed. Only alphanumerics characters (uppercase and lowercase words), underscore, dots and it must be between 5 and 15 characters', - ) + "Username not allowed. Only alphanumerics characters (uppercase and lowercase words), underscore, dots and it must be between 5 and 15 characters" + ); } if (!validator.isEmail(email)) { - return new Error('Invalid email format') + 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 } })) != null) { - return new Error('Email already in use') + return new Error("Email already in use"); } - const salt = await bcrypt.genSalt(15) - const hashedPassword = await bcrypt.hash(password.replace(/ /g, ''), salt) // Removes every space in the string + const salt = await bcrypt.genSalt(15); + const hashedPassword = await bcrypt.hash(password.replace(/ /g, ""), salt); // Removes every space in the string const user = await prisma.user.create({ data: { @@ -53,9 +53,9 @@ async function userSignupService({ username: true, createdAt: true, }, - }) + }); - return user + return user; } -export default userSignupService +export default userSignupService; diff --git a/src/services/users/update-email.ts b/src/services/users/update-email.ts index 91f48ed..46ba27e 100644 --- a/src/services/users/update-email.ts +++ b/src/services/users/update-email.ts @@ -1,24 +1,24 @@ -import type User from 'interfaces/user' -import prisma from 'clients/prisma-client' +import type User from "interfaces/user"; +import prisma from "clients/prisma-client"; async function userUpdateEmailService({ id, email, }: User): Promise | Error> { - const user = await prisma.user.findFirst({ where: { id } }) + const user = await prisma.user.findFirst({ where: { id } }); if (user === null) { - return new Error('User not found') + return new Error("User not found"); } if (user.id !== id) { - return new Error('Forbidden') + return new Error("Forbidden"); } if (email !== undefined && email.trim() !== user.email) { - const existingUser = await prisma.user.findFirst({ where: { email } }) + const existingUser = await prisma.user.findFirst({ where: { email } }); if (existingUser != null && existingUser.email !== user.email) { - return new Error('Email already in use') + return new Error("Email already in use"); } } @@ -34,9 +34,9 @@ async function userUpdateEmailService({ username: true, createdAt: true, }, - }) + }); - return { message: 'Successfully updated user email' } + return { message: "Successfully updated user email" }; } -export default userUpdateEmailService +export default userUpdateEmailService; diff --git a/src/services/users/update-name.ts b/src/services/users/update-name.ts index 07df08e..17a1e25 100644 --- a/src/services/users/update-name.ts +++ b/src/services/users/update-name.ts @@ -1,29 +1,29 @@ -import type User from 'interfaces/user' -import prisma from 'clients/prisma-client' +import type User from "interfaces/user"; +import prisma from "clients/prisma-client"; async function userUpdateNameService({ id, displayName, username, }: User): Promise | Error> { - const user = await prisma.user.findFirst({ where: { id } }) + const user = await prisma.user.findFirst({ where: { id } }); if (user === null) { - return new Error('User not found') + return new Error("User not found"); } // Check if the provided username is different from the current user's data // if different, queries are made to check if the new username is already in use. if (username !== undefined && username.trim() !== user.username) { - const existingUser = await prisma.user.findFirst({ where: { username } }) + const existingUser = await prisma.user.findFirst({ where: { username } }); if (existingUser != null && existingUser.username !== user.username) { - return new Error('Username already in use') + return new Error("Username already in use"); } } if (user.id !== id) { - return new Error('Forbidden') + return new Error("Forbidden"); } const updatedUser = await prisma.user.update({ @@ -39,9 +39,9 @@ async function userUpdateNameService({ username: true, createdAt: true, }, - }) + }); - return updatedUser + return updatedUser; } -export default userUpdateNameService +export default userUpdateNameService; diff --git a/src/services/users/update-password.ts b/src/services/users/update-password.ts index c9af805..a17a687 100644 --- a/src/services/users/update-password.ts +++ b/src/services/users/update-password.ts @@ -1,40 +1,40 @@ -import * as bcrypt from 'bcrypt' -import prisma from 'clients/prisma-client' +import * as bcrypt from "bcrypt"; +import prisma from "clients/prisma-client"; -const passwordRegex = /^(?=.*[0-9])(?=.*[!@#$%^&*_])[a-zA-Z0-9!@#$%^&*_]{8,}$/ +const passwordRegex = /^(?=.*[0-9])(?=.*[!@#$%^&*_])[a-zA-Z0-9!@#$%^&*_]{8,}$/; async function userUpdatePasswordService( id: string, currentPassword: string, - newPassword: string, + newPassword: string ): Promise | Error> { if (!passwordRegex.test(newPassword)) { return new Error( - 'New password must have at least 8 characters, one number and one special character.', - ) + "New password must have at least 8 characters, one number and one special character." + ); } - const user = await prisma.user.findFirst({ where: { id } }) + const user = await prisma.user.findFirst({ where: { id } }); if (user === null) { - return new Error('User not found') + return new Error("User not found"); } if (user.id !== id) { - return new Error('Forbidden') + return new Error("Forbidden"); } const validPassword = await bcrypt.compare( - currentPassword.replace(/ /g, ''), - user.password, - ) + currentPassword.replace(/ /g, ""), + user.password + ); if (!validPassword) { - return new Error('Invalid password') + return new Error("Invalid password"); } - const salt = await bcrypt.genSalt(15) - const hashedPassword = await bcrypt.hash(newPassword.replace(/ /g, ''), salt) + const salt = await bcrypt.genSalt(15); + const hashedPassword = await bcrypt.hash(newPassword.replace(/ /g, ""), salt); await prisma.user.update({ where: { @@ -48,9 +48,9 @@ async function userUpdatePasswordService( username: true, createdAt: true, }, - }) + }); - return { message: 'Successfully updated user password' } + return { message: "Successfully updated user password" }; } -export default userUpdatePasswordService +export default userUpdatePasswordService; diff --git a/src/services/users/upload-picture.ts b/src/services/users/upload-picture.ts index 5756288..4c8999a 100644 --- a/src/services/users/upload-picture.ts +++ b/src/services/users/upload-picture.ts @@ -1,13 +1,13 @@ -import prisma from 'clients/prisma-client' +import prisma from "clients/prisma-client"; async function userUploadPictureService( authorId: string, - url: string, + url: string ): Promise | Error> { - const user = await prisma.user.findFirst({ where: { id: authorId } }) + const user = await prisma.user.findFirst({ where: { id: authorId } }); if (user == null) { - return new Error('User does not exists') + return new Error("User does not exists"); } const updatedUser = await prisma.user.update({ @@ -20,9 +20,9 @@ async function userUploadPictureService( select: { profileImage: true, }, - }) + }); - return updatedUser + return updatedUser; } -export default userUploadPictureService +export default userUploadPictureService; diff --git a/src/socket/index.ts b/src/socket/index.ts deleted file mode 100644 index caddf52..0000000 --- a/src/socket/index.ts +++ /dev/null @@ -1,44 +0,0 @@ -import prisma from 'clients/prisma-client' -import logger from 'helpers/logger' -import { Server } from 'socket.io' - -// eslint-disable-next-line @typescript-eslint/explicit-function-return-type -export default function createSocketIOInstance(httpServer: any) { - const io = new Server(httpServer, { - cors: { - origin: process.env.CORS_ORIGIN ?? '*', - }, - }) - - io.use(async (socket, next) => { - // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions - if (!socket.handshake.auth?.id) { - const error = new Error() - error.message = 'Unauthorized' - next(error) - } - - await prisma.user.update({ - where: { - id: socket.handshake.auth.id, - }, - data: { - socketId: socket.id, - }, - }) - - next() - }) - - /* - const handleConnection = (socket) => { - // TODO - } - */ - - io.on('connection', _ => { - logger.info('Placeholder') - }) - - return io -}