Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Corrigidas as migrations para criacao do banco de dados #47

Merged
merged 1 commit into from
May 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@ import js from '@eslint/js';
import eslintConfigPrettier from 'eslint-config-prettier';
import { defineFlatConfig } from 'eslint-define-config';
import tsEslint from 'typescript-eslint';
import arrayFuncPlugin from 'eslint-plugin-array-func';
import importPlugin from 'eslint-plugin-import';
import perfectionist from 'eslint-plugin-perfectionist';
import unicornPlugin, { configs as unicornConfig } from 'eslint-plugin-unicorn';
import unicornPlugin from 'eslint-plugin-unicorn';
import vitestPlugin from 'eslint-plugin-vitest';
import globals from 'globals';

Expand Down Expand Up @@ -42,7 +41,6 @@ export default defineFlatConfig([
},
},
plugins: {
'array-func': arrayFuncPlugin,
import: importPlugin,
perfectionist,
},
Expand Down Expand Up @@ -73,6 +71,7 @@ export default defineFlatConfig([
'perfectionist/sort-objects': 'warn',
'perfectionist/sort-union-types': 'warn',

'unicorn/no-null': 'off',
'unicorn/prevent-abbreviations': 'off',
},
settings: {
Expand Down
59 changes: 0 additions & 59 deletions prisma/migrations/20240425225524_create_db/migration.sql

This file was deleted.

35 changes: 0 additions & 35 deletions prisma/migrations/20240426013131_update/migration.sql

This file was deleted.

64 changes: 64 additions & 0 deletions prisma/migrations/20240501131741_init_db/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
-- CreateTable
CREATE TABLE "users" (
"id" TEXT NOT NULL,
"email" TEXT NOT NULL,
"name" TEXT,
"username" TEXT NOT NULL,
"password" TEXT NOT NULL,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"deleted_at" TIMESTAMP(3),

CONSTRAINT "users_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "accounts" (
"id" TEXT NOT NULL,
"avatarUrl" TEXT NOT NULL,
"user_id" TEXT,
"social_media_id" INTEGER,
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMP(3) NOT NULL,

CONSTRAINT "accounts_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "tokens" (
"id" SERIAL NOT NULL,
"auth_token" TEXT,
"token" TEXT,
"issued_at" TIMESTAMP(3),
"expire_in" INTEGER,
"account_id" TEXT NOT NULL,

CONSTRAINT "tokens_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "social_media" (
"id" SERIAL NOT NULL,
"name" TEXT NOT NULL,
"description" TEXT NOT NULL,

CONSTRAINT "social_media_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "users_email_key" ON "users"("email");

-- CreateIndex
CREATE UNIQUE INDEX "users_username_key" ON "users"("username");

-- CreateIndex
CREATE UNIQUE INDEX "tokens_account_id_key" ON "tokens"("account_id");

-- AddForeignKey
ALTER TABLE "accounts" ADD CONSTRAINT "accounts_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "accounts" ADD CONSTRAINT "accounts_social_media_id_fkey" FOREIGN KEY ("social_media_id") REFERENCES "social_media"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "tokens" ADD CONSTRAINT "tokens_account_id_fkey" FOREIGN KEY ("account_id") REFERENCES "accounts"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
52 changes: 49 additions & 3 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,53 @@ datasource db {
}

model User {
id String @id @default(uuid())
email String @unique
password String
id String @id @default(uuid())
email String @unique
name String?
username String @unique
password String
account Account[]
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @default(now()) @map("updated_at")
deletedAt DateTime? @map("deleted_at")

@@map("users")
}

model Account {
id String @id @default(uuid())
avatarUrl String
userId String? @map("user_id")
socialMediaId Int? @map("social_media_id")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")

user User? @relation(fields: [userId], references: [id])
socialMedia SocialMedia? @relation(fields: [socialMediaId], references: [id])
token Token?

@@map("accounts")
}

model Token {
id Int @id @default(autoincrement())
authToken String? @map("auth_token")
token String?
issuedAt DateTime? @map("issued_at")
expireIn Int? @map("expire_in")
accountId String @unique @map("account_id")

account Account? @relation(fields: [accountId], references: [id])

@@map("tokens")
}

model SocialMedia {
id Int @id @default(autoincrement())
name String
description String

account Account[]

@@map("social_media")
}
6 changes: 5 additions & 1 deletion src/features/user/controllers/user-controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@ describe('[Controllers] UserController', () => {

const body = {
email: '[email protected]',
name: 'valid_name',
password: 'valid_password',
username: 'valid_username',
};

req.body = body;
Expand All @@ -70,7 +72,9 @@ describe('[Controllers] UserController', () => {

expect(serviceSpy).toHaveBeenCalledWith({
email: body.email,
name: body.name,
password: body.password,
username: body.username,
});
});

Expand All @@ -88,7 +92,7 @@ describe('[Controllers] UserController', () => {

await userController.create(req, res, next);

expect(res.status).toHaveBeenCalledWith(204);
expect(res.status).toHaveBeenCalledWith(201);
});

it('should call next when an error', async () => {
Expand Down
4 changes: 3 additions & 1 deletion src/features/user/controllers/user-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@ export class UserController implements Controller {

const response = await this.serviceCreate.execute({
email: req.body.email,
name: req.body.name,
password: req.body.password,
username: req.body.username,
});

return res.status(HttpStatusCode.noContent).json(response);
return res.status(HttpStatusCode.created).json(response);
} catch (error) {
next(error);
}
Expand Down
2 changes: 2 additions & 0 deletions src/features/user/models/user-create-model.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
export type UserModel = {
email: string;
id: string;
name: string;
password: string;
username: string;
};

export type UserCreateModel = Omit<UserModel, 'id'>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@ import { database } from '@/shared/infra/database/database.js';
type CreateUserParams = Prisma.Args<typeof database.user, 'create'>['data'];

export class UserRepository {
async create({ email, password }: CreateUserParams) {
const user = await database.user.create({
async create({ email, name, password, username }: CreateUserParams) {
return database.user.create({
data: {
email,
name,
password,
username,
},
});

return user;
}
}
13 changes: 12 additions & 1 deletion src/features/user/services/user-create-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,16 @@ import { UserCreateService } from './user-create-service.js';

const makeSut = () => {
class UserRepositoryStub implements UserRepository {
create({ email, password }: any) {
create({ email, name, password, username }: any) {
return Promise.resolve({
createdAt: new Date(2024, 5, 1),
deletedAt: null,
email,
id: 'valid_id',
name,
password,
updatedAt: new Date(2024, 5, 1),
username,
});
}
}
Expand All @@ -27,12 +32,16 @@ describe('UserCreateService', () => {

await userCreateService.execute({
email: '[email protected]',
name: 'valid_name',
password: 'valid_password',
username: 'valid_username',
});

expect(repositorySpy).toHaveBeenCalledWith({
email: '[email protected]',
name: 'valid_name',
password: 'valid_password',
username: 'valid_username',
});
});

Expand All @@ -45,7 +54,9 @@ describe('UserCreateService', () => {

const response = userCreateService.execute({
email: '[email protected]',
name: 'valid_name',
password: 'valid_password',
username: 'valid_username',
});

await expect(response).rejects.toThrowError();
Expand Down
4 changes: 3 additions & 1 deletion src/features/user/services/user-create-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ import type { Service } from '@/shared/protocols/service.js';
export class UserCreateService implements Service<UserCreateModel> {
constructor(private readonly userRepository: UserRepository) {}

async execute({ email, password }: UserCreateModel) {
async execute({ email, name, password, username }: UserCreateModel) {
await this.userRepository.create({
email,
name,
password,
username,
});
}
}
2 changes: 2 additions & 0 deletions src/features/user/validators/user-create-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import Joi from 'joi';

const userCreateBodySchema = Joi.object({
email: Joi.string().email().required(),
name: Joi.string().required(),
password: Joi.string().required(),
username: Joi.string().required(),
});

export const userCreateSchema = Joi.object({
Expand Down
1 change: 1 addition & 0 deletions src/shared/protocols/http-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export type HttpMethod = 'delete' | 'get' | 'post' | 'put';

export enum HttpStatusCode {
badRequest = 400,
created = 201,
forbidden = 403,
noContent = 204,
notFound = 404,
Expand Down
Loading
Loading