Skip to content

Commit

Permalink
finalizacao da criacao de arquivos para routes, middlewares, errors e…
Browse files Browse the repository at this point in the history
… ajuste de local de criacao de diretorio #3
  • Loading branch information
filipeas committed Apr 8, 2022
1 parent b9d0189 commit 4f7bb87
Show file tree
Hide file tree
Showing 4 changed files with 327 additions and 3 deletions.
35 changes: 32 additions & 3 deletions bin/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ module.exports = { initStructure: initStructure };

const fs = require("fs");
const path = require("path");
const createRoot = require("./root/createRoot.js");
const createTypes = require("./root/createTypes.js");
const createRoot = require("./init/createRoot.js");
const createTypes = require("./init/createTypes.js");
const createInfra = require("./init/createInfra.js");

function initStructure() {
console.log("Iniciando criação da estrutura.");
Expand All @@ -12,6 +13,14 @@ function initStructure() {
const destinationRaiz = path.join(__dirname, "..", "..");// "..", ".."
const destinationTypes = path.join(__dirname, "..", "..", "@types");// "..", ".."
const destinationTypesExpress = path.join(__dirname, "..", "..", "@types", "express");//"..", ".."
const destinationInfraSrc = path.join(__dirname, "..", "..", "src");
const destinationInfraHttp = path.join(__dirname, "..", "..", "src", "http");
const destinationInfraHttpContainer = path.join(__dirname, "..", "..", "src", "http", "container");
const destinationInfraHttpErrors = path.join(__dirname, "..", "..", "src", "http", "errors");
const destinationInfraHttpMiddlewares = path.join(__dirname, "..", "..", "src", "http", "middlewares");
const destinationInfraHttpRoutes = path.join(__dirname, "..", "..", "src", "http", "routes");
const destinationInfraHttpValidation = path.join(__dirname, "..", "..", "src", "http", "validations");
const destinationInfraTypeOrm = path.join(__dirname, "..", "..", "src", "typeorm");

// criar .env.example
createRoot.createFile(destinationRaiz);
Expand All @@ -20,6 +29,26 @@ function initStructure() {
if (!fs.existsSync(destinationTypes)) fs.mkdirSync(destinationTypes);
if (!fs.existsSync(destinationTypesExpress)) fs.mkdirSync(destinationTypesExpress);

// criar diretorio e arquivo @types
// criar arquivos do diretorio @types
createTypes.createFile(destinationTypesExpress);

// cria diretorios para infra
if (!fs.existsSync(destinationInfraSrc)) fs.mkdirSync(destinationInfraSrc);
if (!fs.existsSync(destinationInfraHttp)) fs.mkdirSync(destinationInfraHttp);
if (!fs.existsSync(destinationInfraHttpContainer)) fs.mkdirSync(destinationInfraHttpContainer);
if (!fs.existsSync(destinationInfraHttpErrors)) fs.mkdirSync(destinationInfraHttpErrors);
if (!fs.existsSync(destinationInfraHttpMiddlewares)) fs.mkdirSync(destinationInfraHttpMiddlewares);
if (!fs.existsSync(destinationInfraHttpRoutes)) fs.mkdirSync(destinationInfraHttpRoutes);
if (!fs.existsSync(destinationInfraHttpValidation)) fs.mkdirSync(destinationInfraHttpValidation);
if (!fs.existsSync(destinationInfraTypeOrm)) fs.mkdirSync(destinationInfraTypeOrm);

// cria arquivos do diretorio infra
createInfra.createFile(
destinationInfraHttpContainer,
destinationInfraHttpErrors,
destinationInfraHttpMiddlewares,
destinationInfraHttpRoutes,
destinationInfraHttpValidation,
destinationInfraTypeOrm
);
}
295 changes: 295 additions & 0 deletions bin/init/createInfra.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,295 @@
module.exports = { createFile: createFile };

const fs = require("fs");
const path = require("path");

function createFile(
destinationInfraHttpContainer,
destinationInfraHttpErrors,
destinationInfraHttpMiddlewares,
destinationInfraHttpRoutes,
destinationInfraHttpValidation,
destinationInfraTypeOrm
) {
// cria arquivo http/container/index.ts
fs.appendFile(
path.join(destinationInfraHttpContainer, "index.ts"),
`
import { container } from 'tsyringe';
`, function (err) {
if (err) throw err;
console.log("Arquivo http/container/index.ts criado com sucesso.");
});

// cria arquivo http/errors/AppError
fs.appendFile(
path.join(destinationInfraHttpErrors, "AppError.ts"),
`
export class AppError {
public readonly message!: string;
public readonly status_code!: number;
public readonly type_error!: string;
constructor(message: string, status_code: number, type_error: string) {
this.message = message;
this.status_code = status_code;
this.type_error = type_error;
}
}
`, function (err) {
if (err) throw err;
console.log("Arquivo http/errors/AppError.ts criado com sucesso.");
});

// cria arquivo http/errors/BadRequestError
fs.appendFile(
path.join(destinationInfraHttpErrors, "BadRequestError.ts"),
`
import { AppError } from './AppError';
export class BadRequestError extends AppError {
constructor(message: string) {
super(message, 400, 'bab_request_error');
}
}
`, function (err) {
if (err) throw err;
console.log("Arquivo http/errors/BadRequestError.ts criado com sucesso.");
});

// cria arquivo http/errors/ForbiddenError
fs.appendFile(
path.join(destinationInfraHttpErrors, "ForbiddenError.ts"),
`
import { AppError } from './AppError';
export class ForbiddenError extends AppError {
constructor(message: string) {
super(message, 403, 'forbidden_error');
}
}
`, function (err) {
if (err) throw err;
console.log("Arquivo http/errors/ForbiddenError.ts criado com sucesso.");
});

// cria arquivo http/errors/NotFoundError
fs.appendFile(
path.join(destinationInfraHttpErrors, "NotFoundError.ts"),
`
import { AppError } from './AppError';
export class NotFoundError extends AppError {
constructor(message: string) {
super(message, 404, 'not_found_error');
}
}
`, function (err) {
if (err) throw err;
console.log("Arquivo http/errors/NotFoundError.ts criado com sucesso.");
});

// cria arquivo http/errors/UnauthorizedError
fs.appendFile(
path.join(destinationInfraHttpErrors, "UnauthorizedError.ts"),
`
import { AppError } from './AppError';
type TypeError = 'auth_error' | 'expired_error';
export class UnauthozitedError extends AppError {
constructor(message: string, type_error: TypeError = 'auth_error') {
super(message, 401, type_error);
}
}
`, function (err) {
if (err) throw err;
console.log("Arquivo http/errors/UnauthorizedError.ts criado com sucesso.");
});

// cria arquivo http/middlewares/ensureAuthenticated
fs.appendFile(
path.join(destinationInfraHttpMiddlewares, "ensureAuthenticated.ts"),
`
import { TypeOrmUserRepository } from '@domain/users/infra/typeorm/repositories/TypeOrmUserRepository';
import { BadRequestError } from '@infra/http/errors/BadRequestError';
import { UnauthozitedError } from '@infra/http/errors/UnauthorizedError';
import { NextFunction, Request, Response } from 'express';
import { TokenExpiredError, verify } from 'jsonwebtoken';
interface IPayload {
sub: string;
}
export async function ensureAuthenticated(
request: Request,
response: Response,
next: NextFunction,
) {
const authHeader = request.headers.authorization;
if (!authHeader) {
throw new UnauthozitedError('Falha na autenticação');
}
const [, token] = authHeader.split(' ');
try {
const { sub: id } = verify(token, String(process.env.KEY_AUTH)) as IPayload;
const usersRepository = new TypeOrmUserRepository();
const user = await usersRepository.findById(id);
if (!user) {
throw new BadRequestError('Usuário não encontrado');
}
request.user = {
id: user.id,
};
next();
} catch (error) {
if (error instanceof TokenExpiredError) {
throw new UnauthozitedError('Token expirado', 'expired_error');
}
throw new UnauthozitedError('Token inválido');
}
}
`, function (err) {
if (err) throw err;
console.log("Arquivo http/middlewares/ensureAuthenticated.ts criado com sucesso.");
});

// cria arquivo http/middlewares/handleException
fs.appendFile(
path.join(destinationInfraHttpMiddlewares, "handleException.ts"),
`
import { NextFunction, Request, Response } from 'express';
import { AppError } from '@infra/http/errors/AppError';
import { MulterError } from 'multer';
export async function handleException(
error: AppError | Error,
request: Request,
response: Response,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_next: NextFunction,
): Promise<Response> {
if (error instanceof AppError) {
return response
.status(error.status_code)
.json({ error: error.message, type_error: error.type_error });
}
if (error instanceof MulterError) {
return response.status(400).json({
error: 'Selecione um arquivo válido.',
type_error: 'bad_request_error',
});
}
return response.status(500).json({
error: \`Internal server error - $\{error.message}\`,
type_error: 'server_error',
});
}
`, function (err) {
if (err) throw err;
console.log("Arquivo http/middlewares/handleException.ts criado com sucesso.");
});

// cria arquivo http/middlewares/validation
fs.appendFile(
path.join(destinationInfraHttpMiddlewares, "validation.ts"),
`
import { AnySchema } from 'yup';
import { NextFunction, Request, Response } from 'express';
const validate =
(schema: AnySchema) =>
async (request: Request, response: Response, next: NextFunction) => {
try {
await schema.validate(request.body);
return next();
} catch (error) {
return response.status(400).send(error);
}
};
export default validate;
`, function (err) {
if (err) throw err;
console.log("Arquivo http/middlewares/validation.ts criado com sucesso.");
});

// cria arquivo http/routes/index.ts
fs.appendFile(
path.join(destinationInfraHttpRoutes, "index.ts"),
`
import { response, Router } from 'express';
import { authenticateRouter } from './authenticate.routes';
import { usersRouter } from './users.routes';
const routes = Router();
routes.get('/', (request, response) => {
return response
.json({
author: 'Filipe A.s',
message:
'Welcome to Artisan package!',
})
.send();
});
routes.use('/auth', authenticateRouter);
routes.use('/users', usersRouter);
export { routes };
`, function (err) {
if (err) throw err;
console.log("Arquivo http/routes/index.ts criado com sucesso.");
});

// cria arquivo http/routes/authenticate.routes.ts
fs.appendFile(
path.join(destinationInfraHttpRoutes, "authenticate.routes.ts"),
`
import { Router } from 'express';
import { AuthUserController } from '@domain/users/useCases/auth-user/AuthUserController';
const authenticateRouter = Router();
const authUserController = new AuthUserController();
authenticateRouter.post('/', authUserController.handle);
export { authenticateRouter };
`, function (err) {
if (err) throw err;
console.log("Arquivo http/routes/authenticate.routes.ts criado com sucesso.");
});

// cria arquivo http/routes/user.routes.ts
fs.appendFile(
path.join(destinationInfraHttpRoutes, "user.routes.ts"),
`
import { Router } from 'express';
const usersRouter = Router();
export { usersRouter };
`, function (err) {
if (err) throw err;
console.log("Arquivo http/routes/user.routes.ts criado com sucesso.");
});

// validations
// server.ts
// typeorm
}
File renamed without changes.
File renamed without changes.

0 comments on commit 4f7bb87

Please sign in to comment.