es20231 / eqp7

Equipe 7 - ES 2023.1
https://minigproject.vercel.app
3 stars 5 forks source link

Definir os padrões de código #30

Closed CassianoJunior closed 1 year ago

CassianoJunior commented 1 year ago

Padrões de código


interface ComponentProps { }

const Component = ({ ...props }: ComponentProps) => {
  return (
    <p>Hello, world!</p>
  )
}

export { Component }

Fluxo back-end

Exemplos

// src/entities/user.entity.ts
interface User {
  id: string;
  fullName: string;
  username: string;
  email: string
  emailVerified: boolean;
  password: string;
  biography: string;
  profilePicture: string;

  images?: any[]
  posts?: any[]
  comments?: any[]
  postReactions?: any[]
  commentReactions?: any[]
}

export { User };
// src/services/user.service.ts
import { IUserRepository } from "../repositories/iuser.repository"

const UserService = (repository: IUserRepository) => ({
  getUsers: async () => {
    const { ok, message, payload } = await repository.getUsers()
    return {
      ok,
      message,
      payload
    }
  },

  getUserById: async (id: string) => {
    const { ok, message, payload } = await repository.getUserById(id)
    return {
      ok, 
      message,
      payload
    }
  },

  getUserByUsername: async (username: string) => {
    const { 
      ok, 
      message, 
      payload 
    } = await repository.getUserByUsername(username)
    return { ok, message, payload }
  },

  getUserByEmail: async (email: string) => {
    const { ok, message, payload } = await repository.getUserByEmail(email)
    return { ok, message, payload }
  },

  createUser: async (user: any) => {
    const { ok, message, payload } = await repository.createUser(user)
    return { ok, message, payload }
  },

  updateUser: async (id: string, user: any) => {
    const { ok, message, payload } = await repository.updateUser(id, user)
    return { ok, message, payload }
  },

  deleteUser: async (id: string) => {
    const { ok, message, payload } = await repository.deleteUser(id)
    return { ok, message, payload }
  }
})

export { UserService }
// src/factories/user.factory.ts
import { 
  MemoryUserRepository
} from "../repositories/implementations/memory/user.repository";
import { UserService } from "../services/user.service";

const instantiatedUserService = UserService(MemoryUserRepository)

export { instantiatedUserService };
// src/controllers/user.controller.ts
import { FastifyReply, FastifyRequest } from "fastify";
import { instantiatedUserService } from "../factories/user.factory";
const UserService = instantiatedUserService;

const UserController = {
  getUsers: async (request: FastifyRequest, reply: FastifyReply) => {
    const { ok, message, payload } = await UserService.getUsers();

    if (!ok) reply.code(400).send({ message })

    reply.status(200).send({ message, payload });
  },

  getUserById: async (request: FastifyRequest, reply: FastifyReply) => {
    const { id } = request.params as unknown as {id: string};

    const {ok, message, payload} = await UserService.getUserById(id);

    if (!ok) reply.code(400).send({ message })

    reply.status(200).send({ message, payload });
  },

  getUserByUsername: 
    async (request: FastifyRequest, reply: FastifyReply) => {
      const { username } = request.params as unknown as {username: string};

      const {
        ok, 
        message, 
        payload
      } = await UserService.getUserByUsername(username);

      if (!ok) reply.code(400).send({ message })

      reply.status(200).send({ message, payload });
    },

  getUserByEmail: async (request: FastifyRequest, reply: FastifyReply) => {
    const { email } = request.params as unknown as {email: string};

    const {ok, message, payload} = await UserService.getUserByEmail(email);

    if (!ok) reply.code(400).send({ message })

    reply.status(200).send({ message, payload });
  },

  createUser: async (request: FastifyRequest, reply: FastifyReply) => {
    // Validate request body with Zod

    const user = request.body;

    const {ok, message, payload} = await UserService.createUser(user);

    if (!ok) reply.code(400).send({ message })

    reply.status(201).send({ message, payload });
  },

  updateUser: async (request: FastifyRequest, reply: FastifyReply) => {
    const { id } = request.params as unknown as {id: string};
    const user = request.body;

    const {ok, message, payload} = await UserService.updateUser(id, user);

    if (!ok) reply.code(400).send({ message })

    reply.status(200).send({ message, payload });
  },

  deleteUser: async (request: FastifyRequest, reply: FastifyReply) => {
    const { id } = request.params as unknown as {id: string};

    const {ok, message, payload} = await UserService.deleteUser(id);

    if (!ok) reply.code(400).send({ message })

    reply.status(200).send({ message, payload });
  }
}

export { UserController };
// src/routes/user.routes.ts
import { FastifyInstance, FastifyPluginOptions } from "fastify";
import { UserController } from "../controllers/user.controller";

const UserRoutes = 
  (fastify: FastifyInstance, options: FastifyPluginOptions, done: any) => {
    fastify.get(
      '/users', 
      options, 
      UserController.getUsers
    );
    fastify.get(
      '/users/:id', 
      options, 
      UserController.getUserById
    );
    fastify.get(
      '/users/username/:username', 
      options, 
      UserController.getUserByUsername
    );
    fastify.get(
      '/users/email/:email', 
      options, 
      UserController.getUserByEmail
    );
    fastify.post(
      '/users', 
      options, 
      UserController.createUser
    );
    fastify.put(
      '/users/:id', 
      options, 
      UserController.updateUser
    );
    fastify.delete(
      '/users/:id', 
      options, 
      UserController.deleteUser
    );

    done()
  }

export { UserRoutes };

Registrando as rotas

import Fastify from "fastify";
import { UserRoutes } from "./routes/user.routes";

async function bootstrap() {
  const fastify = Fastify({logger: true})

  fastify.register(UserRoutes)

  await fastify.listen({ port: 3333 });
}

bootstrap();
Amarildo-Jr commented 1 year ago

Por enquanto não tenho nada a adicionar. Caso lembre de algo falo aqui. Confiram se vocês têm algo a adicionar @assis23 @JoseeAugusto @EduardoRibeiroBR

JoseeAugusto commented 1 year ago

Também não tenho por enquanto, está bem claro e explicado.

EduardoRibeiroBR commented 1 year ago

Ok!

CassianoJunior commented 1 year ago

DTO's

Para definir o que será preciso para criar ou atualizar um registro, são usados DTO (Data Transfer Objects).

// src/dtos/user/create-user.dto.ts

type CreateUserDTO = {
  fullName: string
  email: string
  username: string
  password: string
}

export { CreateUserDTO }

Eles são as tipagens para o objeto recebido pelo método create ou update no repository.