Skip to content

Commit

Permalink
chore(api): general cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
luke-h1 committed Aug 4, 2024
1 parent 927ebc7 commit 2133125
Show file tree
Hide file tree
Showing 21 changed files with 273 additions and 191 deletions.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"argon2": "^0.40.3",
"bcryptjs": "^2.4.3",
"better-sqlite3": "^11.1.2",
"body-parser": "^1.20.2",
"compression": "^1.7.4",
"connect-redis": "^6.0.0",
"cors": "^2.8.5",
Expand All @@ -55,6 +56,7 @@
"@commitlint/cli": "^19.3.0",
"@commitlint/config-conventional": "^19.2.2",
"@types/bcryptjs": "^2.4.6",
"@types/body-parser": "^1.19.5",
"@types/compression": "^1.7.5",
"@types/connect-redis": "^0.0.23",
"@types/cors": "^2.8.17",
Expand Down
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions prisma/migrations/20240804192824_datestring/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "pets" ALTER COLUMN "birthDate" SET DATA TYPE TEXT;
12 changes: 12 additions & 0 deletions prisma/migrations/20240804193058_age/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
Warnings:
- You are about to drop the column `type` on the `pets` table. All the data in the column will be lost.
- Added the required column `age` to the `pets` table without a default value. This is not possible if the table is not empty.
- Added the required column `description` to the `pets` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "pets" DROP COLUMN "type",
ADD COLUMN "age" TEXT NOT NULL,
ADD COLUMN "description" TEXT NOT NULL;
21 changes: 21 additions & 0 deletions prisma/migrations/20240804193431_drop_tags/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
Warnings:
- You are about to drop the `_PetToTag` table. If the table is not empty, all the data it contains will be lost.
- You are about to drop the `tags` table. If the table is not empty, all the data it contains will be lost.
*/
-- DropForeignKey
ALTER TABLE "_PetToTag" DROP CONSTRAINT "_PetToTag_A_fkey";

-- DropForeignKey
ALTER TABLE "_PetToTag" DROP CONSTRAINT "_PetToTag_B_fkey";

-- AlterTable
ALTER TABLE "pets" ADD COLUMN "tags" TEXT[];

-- DropTable
DROP TABLE "_PetToTag";

-- DropTable
DROP TABLE "tags";
17 changes: 9 additions & 8 deletions prisma/schema/pet.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,15 @@ enum PetStatus {
}

model Pet {
id String @id @default(uuid())
name String
type String
breed String
status PetStatus @default(AVAILABLE)
birthDate DateTime
photoUrl String
tags Tag[]
id String @id @default(uuid())
name String
description String
age String
breed String
status PetStatus @default(AVAILABLE)
birthDate String
photoUrl String
tags String[]
creatorId String
creator User @relation(fields: [creatorId], references: [id])
Expand Down
9 changes: 0 additions & 9 deletions prisma/schema/tag.prisma

This file was deleted.

2 changes: 1 addition & 1 deletion prisma/schema/user.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ model User {
password String
pets Pet[]
role Role @default(USER)
role Role @default(USER)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
Expand Down
36 changes: 24 additions & 12 deletions src/controllers/__mocks__/pet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,50 +4,62 @@ export const pets: Omit<Pet, 'createdAt' | 'updatedAt' | 'id' | 'creatorId'>[] =
[
{
name: 'Buddy',
type: 'dog',
breed: 'Golden Retriever',
status: 'AVAILABLE',
birthDate: new Date('2019-01-01'),
age: '12',
birthDate: '2022',
description: 'dog',
tags: ['dog'],
photoUrl: 'https://images.unsplash.com/photo-1560807707-8cc777a4d2f9',
},
{
name: 'Mittens',
type: 'cat',
breed: 'Siamese',
status: 'ADOPTED',
birthDate: new Date('2020-05-15'),
age: '12',
birthDate: '2022',
description: 'dog',
tags: ['dog'],
photoUrl: 'https://images.unsplash.com/photo-1592194996308-7d9c3f8d4a2b',
},
{
name: 'Charlie',
type: 'dog',
breed: 'Labrador Retriever',
status: 'AVAILABLE',
birthDate: new Date('2018-07-22'),
age: '12',
birthDate: '2022',
description: 'dog',
tags: ['dog'],
photoUrl: 'https://images.unsplash.com/photo-1517423440428-a5a00ad493e8',
},
{
name: 'Whiskers',
type: 'cat',
breed: 'Maine Coon',
status: 'PENDING',
birthDate: new Date('2017-11-11'),
age: '12',
birthDate: '2022',
description: 'dog',
tags: ['dog'],
photoUrl: 'https://images.unsplash.com/photo-1560807707-8cc777a4d2f9',
},
{
name: 'Max',
type: 'dog',
breed: 'Beagle',
status: 'ADOPTED',
birthDate: new Date('2016-03-30'),
age: '12',
birthDate: '2022',
description: 'dog',
tags: ['dog'],
photoUrl: 'https://images.unsplash.com/photo-1558788353-f76d92427f16',
},
{
name: 'Luna',
type: 'cat',
breed: 'Bengal',
status: 'AVAILABLE',
birthDate: new Date('2021-02-14'),
age: '12',
birthDate: '2022',
description: 'dog',
tags: ['dog'],
photoUrl: 'https://images.unsplash.com/photo-1592194996308-7d9c3f8d4a2b',
},
];
5 changes: 4 additions & 1 deletion src/controllers/__tests__/authController.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@ describe('auth', () => {

expect(statusCode).toBe(201);

expect(body).toEqual({ id: expect.any(String) });
expect(body).toEqual({
id: expect.any(String),
email: expect.any(String),
});
});

test('returns bad request when user exists', async () => {
Expand Down
49 changes: 0 additions & 49 deletions src/controllers/__tests__/petController.test.ts

This file was deleted.

100 changes: 47 additions & 53 deletions src/controllers/authController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,7 @@ import omit from 'lodash/omit';
import BadRequestError from '../errors/BadRequestError';
import NotFoundError from '../errors/NotFoundError';
import { authErrorCodes } from '../errors/auth';
import {
LoginRequest,
RegisterRequest,
ResetPasswordRequest,
} from '../requests/auth';
import { LoginRequest, RegisterRequest } from '../requests/auth';
import AuthService from '../services/authService';
import logger from '../utils/logger';

Expand Down Expand Up @@ -40,56 +36,54 @@ export default class AuthController {
});
}

req.session.userId = result?.id;
// req.session.userId = result?.id;

return res.status(201).json(omit(result, 'password'));
}

async login(req: LoginRequest, res: Response) {
const result = await this.authService.login(req.body);

switch (result) {
case authErrorCodes.InvalidCredentials: {
throw new BadRequestError({
message: 'Invalid credentials',
statusCode: 401,
type: 'Unauthorized',
code: authErrorCodes.InvalidCredentials,
title: 'Bad credentials supplied',
errors: [
{
code: 'invalid_type',
expected: 'string',
received: 'undefined',
path: ['body', 'email'],
message: 'Invalid email or password',
},
],
});
}

case authErrorCodes.UserNotFound: {
throw new NotFoundError({
code: authErrorCodes.UserNotFound,
title: 'User not found',
statusCode: 404,
message: 'User not found',
errors: [
{
code: 'invalid_type',
expected: 'string',
received: 'undefined',
path: ['body', 'email'],
message: 'User not found',
},
],
});
}
if (result === authErrorCodes.InvalidCredentials) {
throw new BadRequestError({
message: 'Invalid credentials',
statusCode: 401,
type: 'Unauthorized',
code: authErrorCodes.InvalidCredentials,
title: 'Bad credentials supplied',
errors: [
{
code: 'invalid_type',
expected: 'string',
received: 'undefined',
path: ['body', 'email'],
message: 'Invalid email or password',
},
],
});
}

default:
req.session.userId = result.id;
return res.status(200).json(omit(result, 'password'));
if (result === authErrorCodes.UserNotFound) {
throw new NotFoundError({
code: authErrorCodes.UserNotFound,
title: 'User not found',
statusCode: 404,
message: 'User not found',
errors: [
{
code: 'invalid_type',
expected: 'string',
received: 'undefined',
path: ['body', 'email'],
message: 'User not found',
},
],
});
}
req.session.userId = result.id;
// auth user with express-session

return res.status(200).json(omit(result, 'password'));
}

async logout(req: Request, res: Response) {
Expand All @@ -104,15 +98,15 @@ export default class AuthController {
});
}

async resetPassword(req: ResetPasswordRequest, res: Response) {
const result = await this.authService.resetPassword(req.body);
// async resetPassword(req: ResetPasswordRequest, res: Response) {
// const result = await this.authService.resetPassword(req.body);

if (result) {
return res.status(200).json({ message: 'Password reset' });
}
// if (result) {
// return res.status(200).json({ message: 'Password reset' });
// }

return res.status(400).json({ message: 'Password reset failed' });
}
// return res.status(400).json({ message: 'Password reset failed' });
// }

async deleteAccount(req: Request, res: Response) {
const result = await this.authService.deleteAccount(req.body);
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class Main {

public async start() {
await this.validateEnvironmentVariables();
const app = await CreateServer.init();
const app = CreateServer.init();
const port = process.env.PORT || 8000;

app.listen(port, () => {
Expand Down
Loading

0 comments on commit 2133125

Please sign in to comment.