From ce9164d77df11c48eaa97324c744e33f175d7757 Mon Sep 17 00:00:00 2001 From: Talysson Date: Thu, 30 Sep 2021 10:13:30 -0300 Subject: [PATCH] Move codebase to use single quotes --- .prettierrc | 2 +- bin/replClient.ts | 14 ++--- src/__tests__/TestControls.ts | 12 ++-- src/__tests__/setup.ts | 4 +- src/_boot/appModules.ts | 6 +- src/_boot/database.ts | 10 +-- src/_boot/index.ts | 22 +++---- src/_boot/pubSub.ts | 12 ++-- src/_boot/repl.ts | 22 +++---- src/_boot/server.ts | 26 ++++---- src/_boot/swagger.ts | 12 ++-- src/_lib/Application.ts | 62 +++++++++---------- src/_lib/CQRS.d.ts | 2 +- src/_lib/Context.ts | 16 ++--- src/_lib/DDD.d.ts | 2 +- src/_lib/Environment.ts | 14 ++--- src/_lib/IdProvider.ts | 6 +- src/_lib/MongoProvider.ts | 6 +- src/_lib/Predicate.ts | 2 +- src/_lib/WithInvariants.ts | 4 +- src/_lib/di/containerAdapters.ts | 4 +- src/_lib/errors/BadRequestError.ts | 6 +- src/_lib/errors/ForbiddenError.ts | 8 +-- src/_lib/errors/NotFoundError.ts | 6 +- src/_lib/errors/UnauthorizedError.ts | 8 +-- src/_lib/errors/ValidationError.ts | 8 +-- src/_lib/events/EventConsumer.ts | 8 +-- src/_lib/events/EventProvider.ts | 8 +-- src/_lib/events/Publisher.d.ts | 2 +- src/_lib/events/Subscriber.d.ts | 4 +- src/_lib/http/handler.ts | 8 +-- src/_lib/http/middlewares/errorHandler.ts | 8 +-- src/_lib/http/middlewares/gracefulShutdown.ts | 16 ++--- src/_lib/http/middlewares/requestContainer.ts | 6 +- src/_lib/http/middlewares/requestId.ts | 4 +- src/_lib/http/runAsync.ts | 2 +- src/_lib/http/validation/Paginator.ts | 36 +++++------ src/_lib/http/validation/Validator.ts | 28 ++++----- src/_lib/logger/index.ts | 2 +- src/_lib/message/MessageBundle.ts | 14 ++--- src/_lib/pubSub/EventEmitterConsumer.ts | 4 +- src/_lib/pubSub/EventEmitterProvider.ts | 4 +- src/_lib/pubSub/EventEmitterPubSub.ts | 10 +-- src/_sharedKernel/domain/ArticleId.d.ts | 2 +- .../domain/error/BusinessError.ts | 6 +- .../infrastructure/ArticleIdProvider.ts | 6 +- src/_sharedKernel/infrastructure/MemoryDB.ts | 4 +- .../interface/http/ErrorConverters.ts | 22 +++---- .../interface/http/ArticleController.spec.ts | 30 ++++----- .../unit/application/CreateArticle.test.ts | 22 +++---- .../unit/application/DeleteArticle.test.ts | 26 ++++---- .../unit/application/PublishArticle.test.ts | 30 ++++----- .../application/events/ArticleCreatedEvent.ts | 10 +-- .../application/useCases/CreateArticle.ts | 10 +-- .../application/useCases/DeleteArticle.ts | 6 +- .../application/useCases/PublishArticle.ts | 16 ++--- src/article/domain/Article.ts | 18 +++--- src/article/domain/ArticleRepository.d.ts | 4 +- src/article/index.ts | 32 +++++----- .../infrastructure/ArticleCollection.ts | 8 +-- src/article/infrastructure/ArticleMapper.ts | 12 ++-- .../infrastructure/MongoArticleRepository.ts | 16 ++--- .../email/ArticleCreatedEmailListener.ts | 8 +-- .../articleController/CreateArticleHandler.ts | 12 ++-- .../articleController/DeleteArticleHandler.ts | 4 +- .../articleController/FindArticlesHandler.ts | 8 +-- .../PublishArticleHandler.ts | 6 +- .../interface/http/articleController/index.ts | 18 +++--- src/article/messages.ts | 6 +- src/article/query/FindArticles.d.ts | 2 +- src/article/query/impl/MongoFindArticles.ts | 24 +++---- .../application/useCases/CreateComment.ts | 8 +-- src/comment/domain/Comment.ts | 12 ++-- src/comment/domain/CommentId.d.ts | 2 +- src/comment/domain/CommentRepository.d.ts | 8 +-- src/comment/index.ts | 20 +++--- .../infrastructure/CommentCollection.ts | 8 +-- .../infrastructure/CommentIdProvider.ts | 6 +- src/comment/infrastructure/CommentMapper.ts | 14 ++--- .../infrastructure/MongoCommentRepository.ts | 18 +++--- .../commentController/CreateCommentHandler.ts | 8 +-- .../interface/http/commentController/index.ts | 6 +- src/config.ts | 38 ++++++------ src/container.ts | 12 ++-- src/context.ts | 10 +-- src/index.ts | 10 +-- src/messages.ts | 4 +- 87 files changed, 506 insertions(+), 506 deletions(-) diff --git a/.prettierrc b/.prettierrc index 8ce0532..5d0c691 100644 --- a/.prettierrc +++ b/.prettierrc @@ -2,5 +2,5 @@ "arrowParens": "always", "printWidth": 120, "semi": true, - "singleQuote": false + "singleQuote": true } diff --git a/bin/replClient.ts b/bin/replClient.ts index d7691bc..8ecf4e9 100644 --- a/bin/replClient.ts +++ b/bin/replClient.ts @@ -1,9 +1,9 @@ -import { connect } from "net"; +import { connect } from 'net'; const main = () => { const { argv } = process; - let host = "127.0.0.1"; + let host = '127.0.0.1'; let port = 2580; if (argv.length === 4) { @@ -12,7 +12,7 @@ const main = () => { } else if (argv.length === 3) { port = Number(argv[2]); } else { - throw new Error("The command is supposed to be used as: yarn remote [server address] [REPL port]"); + throw new Error('The command is supposed to be used as: yarn remote [server address] [REPL port]'); } const sock = connect(port, host); @@ -20,18 +20,18 @@ const main = () => { process.stdin.pipe(sock); sock.pipe(process.stdout); - sock.on("connect", function () { + sock.on('connect', function () { process.stdin.resume(); process.stdin.setRawMode(true); }); - sock.on("close", function done() { + sock.on('close', function done() { process.stdin.setRawMode(false); process.stdin.pause(); - sock.removeListener("close", done); + sock.removeListener('close', done); }); - process.stdin.on("end", function () { + process.stdin.on('end', function () { sock.destroy(); console.log(); }); diff --git a/src/__tests__/TestControls.ts b/src/__tests__/TestControls.ts index 368cdb3..871b119 100644 --- a/src/__tests__/TestControls.ts +++ b/src/__tests__/TestControls.ts @@ -1,8 +1,8 @@ -import { Container, container } from "@/container"; -import { withContext } from "@/context"; -import { main } from "@/_boot"; -import { Db } from "mongodb"; -import supertest, { SuperTest, Test } from "supertest"; +import { Container, container } from '@/container'; +import { withContext } from '@/context'; +import { main } from '@/_boot'; +import { Db } from 'mongodb'; +import supertest, { SuperTest, Test } from 'supertest'; type Dependencies = { mongo: Db; @@ -13,7 +13,7 @@ type TestControls = Readonly<{ clearDatabase: () => Promise; cleanUp: () => Promise; container: Container; - registry: Container["cradle"]; + registry: Container['cradle']; }>; const appRunning = withContext( diff --git a/src/__tests__/setup.ts b/src/__tests__/setup.ts index 4b54826..679f780 100644 --- a/src/__tests__/setup.ts +++ b/src/__tests__/setup.ts @@ -1,4 +1,4 @@ -process.env.NODE_ENV = "test"; +process.env.NODE_ENV = 'test'; const catchAll = new Proxy( {}, @@ -9,6 +9,6 @@ const catchAll = new Proxy( } ); -jest.mock("pino", () => () => catchAll); +jest.mock('pino', () => () => catchAll); console = catchAll; diff --git a/src/_boot/appModules.ts b/src/_boot/appModules.ts index f3a5103..92f477f 100644 --- a/src/_boot/appModules.ts +++ b/src/_boot/appModules.ts @@ -1,6 +1,6 @@ -import { articleModule, ArticleRegistry } from "@/article"; -import { ArticleMessages } from "@/article/messages"; -import { commentModule, CommentRegistry } from "@/comment"; +import { articleModule, ArticleRegistry } from '@/article'; +import { ArticleMessages } from '@/article/messages'; +import { commentModule, CommentRegistry } from '@/comment'; type AppModulesMessages = ArticleMessages; diff --git a/src/_boot/database.ts b/src/_boot/database.ts index d17d819..2e5a91d 100644 --- a/src/_boot/database.ts +++ b/src/_boot/database.ts @@ -1,7 +1,7 @@ -import { makeModule } from "@/context"; -import { makeMongoProvider, MongoProvider } from "@/_lib/MongoProvider"; -import { asValue } from "awilix"; -import { Db, MongoClient } from "mongodb"; +import { makeModule } from '@/context'; +import { makeMongoProvider, MongoProvider } from '@/_lib/MongoProvider'; +import { asValue } from 'awilix'; +import { Db, MongoClient } from 'mongodb'; type DatabaseConfig = { mongodb: { @@ -12,7 +12,7 @@ type DatabaseConfig = { }; }; -const database = makeModule("database", async ({ container: { register }, config: { mongodb } }) => { +const database = makeModule('database', async ({ container: { register }, config: { mongodb } }) => { const client = new MongoClient(mongodb.host, { auth: { username: mongodb.username, password: mongodb.password }, }); diff --git a/src/_boot/index.ts b/src/_boot/index.ts index 7051116..a79ee06 100644 --- a/src/_boot/index.ts +++ b/src/_boot/index.ts @@ -1,14 +1,14 @@ -import { server } from "@/_boot/server"; -import { appModules } from "@/_boot/appModules"; -import { asValue } from "awilix"; -import { database } from "@/_boot/database"; -import { repl } from "@/_boot/repl"; -import { withContext } from "@/context"; -import { Configuration } from "@/config"; -import { Logger } from "pino"; -import { pubSub } from "@/_boot/pubSub"; -import { MessageBundle } from "@/messages"; -import { swagger } from "@/_boot/swagger"; +import { server } from '@/_boot/server'; +import { appModules } from '@/_boot/appModules'; +import { asValue } from 'awilix'; +import { database } from '@/_boot/database'; +import { repl } from '@/_boot/repl'; +import { withContext } from '@/context'; +import { Configuration } from '@/config'; +import { Logger } from 'pino'; +import { pubSub } from '@/_boot/pubSub'; +import { MessageBundle } from '@/messages'; +import { swagger } from '@/_boot/swagger'; const main = withContext(async ({ app, container, config, bootstrap, logger, messageBundle }) => { container.register({ diff --git a/src/_boot/pubSub.ts b/src/_boot/pubSub.ts index 373312e..05d5001 100644 --- a/src/_boot/pubSub.ts +++ b/src/_boot/pubSub.ts @@ -1,10 +1,10 @@ -import { makeModule } from "@/context"; -import { makeEventEmitterPubSub } from "@/_lib/pubSub/EventEmitterPubSub"; -import { asValue } from "awilix"; -import { Subscriber } from "@/_lib/events/Subscriber"; -import { Publisher } from "@/_lib/events/Publisher"; +import { makeModule } from '@/context'; +import { makeEventEmitterPubSub } from '@/_lib/pubSub/EventEmitterPubSub'; +import { asValue } from 'awilix'; +import { Subscriber } from '@/_lib/events/Subscriber'; +import { Publisher } from '@/_lib/events/Publisher'; -const pubSub = makeModule("pubSub", async ({ container: { build, register }, app: { onReady } }) => { +const pubSub = makeModule('pubSub', async ({ container: { build, register }, app: { onReady } }) => { const eventEmitterPubSub = build(makeEventEmitterPubSub); register({ diff --git a/src/_boot/repl.ts b/src/_boot/repl.ts index c866330..815771d 100644 --- a/src/_boot/repl.ts +++ b/src/_boot/repl.ts @@ -1,7 +1,7 @@ -import REPL, { REPLEval, ReplOptions, REPLServer } from "repl"; -import vm from "vm"; -import { createServer, Server } from "net"; -import { makeModule } from "@/context"; +import REPL, { REPLEval, ReplOptions, REPLServer } from 'repl'; +import vm from 'vm'; +import { createServer, Server } from 'net'; +import { makeModule } from '@/context'; type REPLConfig = { appName: string; @@ -12,7 +12,7 @@ type REPLConfig = { }; const repl = makeModule( - "repl", + 'repl', async ({ app: { onReady, terminate }, container, @@ -34,7 +34,7 @@ const repl = makeModule( return callback(null, result); }; - const isPromise = (value) => value && typeof value.then === "function" && typeof value.catch === "function"; + const isPromise = (value) => value && typeof value.then === 'function' && typeof value.catch === 'function'; const createREPL = ( config: Partial = { input: process.stdin, output: process.stdout } @@ -57,8 +57,8 @@ const repl = makeModule( if (cli) { const repl = createREPL(); - repl.on("close", terminate); - } else if (!["production", "test"].includes(environment)) { + repl.on('close', terminate); + } else if (!['production', 'test'].includes(environment)) { server = createServer((socket) => { const repl = createREPL({ input: socket, @@ -66,12 +66,12 @@ const repl = makeModule( terminal: true, }); - repl.on("close", () => { + repl.on('close', () => { socket.end(); }); - socket.on("error", (err) => { - logger.error("[REPL] Connection error"); + socket.on('error', (err) => { + logger.error('[REPL] Connection error'); logger.error(err); socket.end(); }); diff --git a/src/_boot/server.ts b/src/_boot/server.ts index b81af41..2380185 100644 --- a/src/_boot/server.ts +++ b/src/_boot/server.ts @@ -1,13 +1,13 @@ -import express, { Router, Application, json, urlencoded } from "express"; -import { asValue } from "awilix"; -import httpLogger from "pino-http"; -import { createServer } from "http"; -import { requestId } from "@/_lib/http/middlewares/requestId"; -import { requestContainer } from "@/_lib/http/middlewares/requestContainer"; -import { errorHandler } from "@/_lib/http/middlewares/errorHandler"; -import { makeModule } from "@/context"; -import { gracefulShutdown } from "@/_lib/http/middlewares/gracefulShutdown"; -import { errorConverters } from "@/_sharedKernel/interface/http/ErrorConverters"; +import express, { Router, Application, json, urlencoded } from 'express'; +import { asValue } from 'awilix'; +import httpLogger from 'pino-http'; +import { createServer } from 'http'; +import { requestId } from '@/_lib/http/middlewares/requestId'; +import { requestContainer } from '@/_lib/http/middlewares/requestContainer'; +import { errorHandler } from '@/_lib/http/middlewares/errorHandler'; +import { makeModule } from '@/context'; +import { gracefulShutdown } from '@/_lib/http/middlewares/gracefulShutdown'; +import { errorConverters } from '@/_sharedKernel/interface/http/ErrorConverters'; type ServerConfig = { http: { @@ -17,7 +17,7 @@ type ServerConfig = { }; const server = makeModule( - "server", + 'server', async ({ app: { onBooted, onReady }, container, config: { cli, http, environment }, logger }) => { const { register } = container; const server = express(); @@ -36,7 +36,7 @@ const server = makeModule( const rootRouter = Router(); const apiRouter = Router(); - rootRouter.use("/api", apiRouter); + rootRouter.use('/api', apiRouter); server.use(rootRouter); @@ -48,7 +48,7 @@ const server = makeModule( server.use(errorHandler(errorConverters, { logger })); }); - if (!cli && environment !== "test") { + if (!cli && environment !== 'test') { onReady( async () => new Promise((resolve) => { diff --git a/src/_boot/swagger.ts b/src/_boot/swagger.ts index b8b277c..cc50e01 100644 --- a/src/_boot/swagger.ts +++ b/src/_boot/swagger.ts @@ -1,7 +1,7 @@ -import { makeModule } from "@/context"; -import { resolve } from "path"; -import swaggerJSDoc from "swagger-jsdoc"; -import swaggerUi from "swagger-ui-express"; +import { makeModule } from '@/context'; +import { resolve } from 'path'; +import swaggerJSDoc from 'swagger-jsdoc'; +import swaggerUi from 'swagger-ui-express'; type SwaggerConfig = { swagger: { @@ -12,7 +12,7 @@ type SwaggerConfig = { }; }; -const swagger = makeModule("swagger", async ({ container: { build }, config: { http, swagger } }) => { +const swagger = makeModule('swagger', async ({ container: { build }, config: { http, swagger } }) => { const options = { swaggerDefinition: { info: { @@ -22,7 +22,7 @@ const swagger = makeModule("swagger", async ({ container: { build }, config: { h host: `${http.host}:${http.port}`, basePath: swagger.basePath, }, - apis: [resolve(__dirname, "../**/interface/http/**/*.yaml"), resolve(__dirname, "../**/interface/http/**/*.ts")], + apis: [resolve(__dirname, '../**/interface/http/**/*.yaml'), resolve(__dirname, '../**/interface/http/**/*.ts')], }; // Initialize swagger-jsdoc -> returns validated swagger spec in json format diff --git a/src/_lib/Application.ts b/src/_lib/Application.ts index 25f2a7a..1b4e016 100644 --- a/src/_lib/Application.ts +++ b/src/_lib/Application.ts @@ -7,18 +7,18 @@ type HookStore = { }; enum Lifecycle { - BOOTING = "BOOTING", - BOOTED = "BOOTED", - READY = "READY", - RUNNING = "RUNNING", - DISPOSING = "DISPOSING", - DISPOSED = "DISPOSED", + BOOTING = 'BOOTING', + BOOTED = 'BOOTED', + READY = 'READY', + RUNNING = 'RUNNING', + DISPOSING = 'DISPOSING', + DISPOSED = 'DISPOSED', } type LifecycleHooks = { [key in `on${Capitalize>}`]: ( fn: HookFn | HookFn[], - order?: "append" | "prepend" + order?: 'append' | 'prepend' ) => void; }; @@ -32,7 +32,7 @@ type Application = { type ApplicationOptions = { shutdownTimeout: number; - logger: Pick; + logger: Pick; }; const makeApp = ({ logger, shutdownTimeout }: ApplicationOptions): Application => { @@ -43,7 +43,7 @@ const makeApp = ({ logger, shutdownTimeout }: ApplicationOptions): Application = const started: HookFn = () => new Promise((resolve) => { - logger.info("Application started"); + logger.info('Application started'); appState = AppState.STARTED; @@ -57,9 +57,9 @@ const makeApp = ({ logger, shutdownTimeout }: ApplicationOptions): Application = const transition = (lifecycle: Lifecycle) => () => promiseChain(hooks.get(lifecycle)); const start = memo(async () => { - if (appState !== AppState.IDLE) throw new Error("The application has already started."); + if (appState !== AppState.IDLE) throw new Error('The application has already started.'); - logger.info("Starting application"); + logger.info('Starting application'); try { await promiseChain([ @@ -78,14 +78,14 @@ const makeApp = ({ logger, shutdownTimeout }: ApplicationOptions): Application = }); const stop = memo(async () => { - if (appState === AppState.IDLE) throw new Error("The application is not running."); + if (appState === AppState.IDLE) throw new Error('The application is not running.'); if (release) { release(); release = null; } - logger.info("Stopping application"); + logger.info('Stopping application'); await promiseChain([ status(AppState.STOPPING), @@ -96,8 +96,8 @@ const makeApp = ({ logger, shutdownTimeout }: ApplicationOptions): Application = setTimeout(() => { logger.warn( - "The stop process has finished but something is keeping the application from exiting. " + - "Check your cleanup process!" + 'The stop process has finished but something is keeping the application from exiting. ' + + 'Check your cleanup process!' ); }, 5000).unref(); }); @@ -105,19 +105,19 @@ const makeApp = ({ logger, shutdownTimeout }: ApplicationOptions): Application = let forceShutdown = false; const shutdown = (code: number) => async () => { - process.stdout.write("\n"); + process.stdout.write('\n'); setTimeout(() => { - logger.error("Ok, my patience is over! #ragequit"); + logger.error('Ok, my patience is over! #ragequit'); process.exit(code); }, shutdownTimeout).unref(); if ((appState === AppState.STOPPING || appState === AppState.STOPPED) && code === 0) { if (forceShutdown) { - process.kill(process.pid, "SIGKILL"); + process.kill(process.pid, 'SIGKILL'); } - logger.warn("The application is yet to finishing the shutdown process. Repeat the command to force exit"); + logger.warn('The application is yet to finishing the shutdown process. Repeat the command to force exit'); forceShutdown = true; return; } @@ -131,24 +131,24 @@ const makeApp = ({ logger, shutdownTimeout }: ApplicationOptions): Application = process.exit(code); }; - const terminate = () => process.kill(process.pid, "SIGTERM"); + const terminate = () => process.kill(process.pid, 'SIGTERM'); - process.on("SIGTERM", shutdown(0)); - process.on("SIGINT", shutdown(0)); - process.on("uncaughtException", shutdown(1)); - process.on("unhandledRejection", shutdown(1)); + process.on('SIGTERM', shutdown(0)); + process.on('SIGINT', shutdown(0)); + process.on('uncaughtException', shutdown(1)); + process.on('unhandledRejection', shutdown(1)); const lifecycleHooks = ( decorator: (lifecycle: Lifecycle, fn: HookFn | HookFn[]) => HookFn | HookFn[] = (lifecycle, fn) => fn ) => { - const once = (lifecycle, fn, order = "append") => { + const once = (lifecycle, fn, order = 'append') => { const decoratedFn = decorator(lifecycle, fn); Array.isArray(decoratedFn) ? hooks[order](lifecycle, ...decoratedFn) : hooks[order](lifecycle, decoratedFn); }; return Object.keys(Lifecycle).reduce( (acc, hook) => ({ ...acc, - [`on${capitalize(hook)}`]: (fn: HookFn | HookFn[], order?: "append" | "prepend") => + [`on${capitalize(hook)}`]: (fn: HookFn | HookFn[], order?: 'append' | 'prepend') => once(Lifecycle[hook], fn, order), }), {} @@ -171,11 +171,11 @@ const makeApp = ({ logger, shutdownTimeout }: ApplicationOptions): Application = }; enum AppState { - IDLE = "IDLE", - STARTING = "STARTING", - STARTED = "STARTED", - STOPPING = "STOPPING", - STOPPED = "STOPED", + IDLE = 'IDLE', + STARTING = 'STARTING', + STARTED = 'STARTED', + STOPPING = 'STOPPING', + STOPPED = 'STOPED', } const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1).toLowerCase(); diff --git a/src/_lib/CQRS.d.ts b/src/_lib/CQRS.d.ts index 796e989..7ee0e3c 100644 --- a/src/_lib/CQRS.d.ts +++ b/src/_lib/CQRS.d.ts @@ -1,6 +1,6 @@ type Sort = Readonly<{ field: string; - direction: "asc" | "desc"; + direction: 'asc' | 'desc'; }>; type Pagination = Readonly<{ diff --git a/src/_lib/Context.ts b/src/_lib/Context.ts index 3bca0cf..f532e65 100644 --- a/src/_lib/Context.ts +++ b/src/_lib/Context.ts @@ -1,4 +1,4 @@ -import { Application, HookFn, makeApp } from "@/_lib/Application"; +import { Application, HookFn, makeApp } from '@/_lib/Application'; type EntrypointFn> = (arg: Context) => Promise; @@ -10,7 +10,7 @@ type Module, F extends BootFn = BootFn }; type Context> = { - app: Omit; + app: Omit; bootstrap: []>(...modules: M) => Promise; } & T; @@ -21,7 +21,7 @@ type ContextProvider> = { type ContextOptions = { shutdownTimeout: number; - logger: Pick; + logger: Pick; }; const defaultOptions: ContextOptions = { @@ -41,7 +41,7 @@ const makeContext = >( const bootstrap = async []>(...modules: M): Promise => { if (!modules.every((module) => module[moduleKey])) { const foreignModules = modules.filter((module) => !module[moduleKey]).map((module) => module.name); - throw new Error(`Foreign module(s) provided for bootstrap function: ${foreignModules.join(", ")}`); + throw new Error(`Foreign module(s) provided for bootstrap function: ${foreignModules.join(', ')}`); } const bootOrder = modules.map(({ name, fn }) => async () => { @@ -53,14 +53,14 @@ const makeContext = >( app: app.decorateHooks((lifecycle, fn) => async () => { const isArray = Array.isArray(fn); - logger.info(`Running ${lifecycle.toLowerCase()} hook${isArray ? "s" : ""} from ${name} module.`); + logger.info(`Running ${lifecycle.toLowerCase()} hook${isArray ? 's' : ''} from ${name} module.`); return (Array.isArray(fn) ? fn : [fn]).reduce( (chain, hook) => chain.then(() => hook().catch((err) => { logger.error( - `Error while performing ${lifecycle.toLowerCase()} hook${isArray ? "s" : ""} from ${name} module.` + `Error while performing ${lifecycle.toLowerCase()} hook${isArray ? 's' : ''} from ${name} module.` ); logger.error(err); }) @@ -71,7 +71,7 @@ const makeContext = >( }) ); - if (typeof result === "function") { + if (typeof result === 'function') { app.onDisposing(async () => { logger.info(`Disposing ${name} module.`); @@ -79,7 +79,7 @@ const makeContext = >( logger.error(`Error while disposing of ${name} module. Trying to resume teardown`); logger.error(err); }); - }, "prepend"); + }, 'prepend'); } }); diff --git a/src/_lib/DDD.d.ts b/src/_lib/DDD.d.ts index 6d7f89b..0cac19d 100644 --- a/src/_lib/DDD.d.ts +++ b/src/_lib/DDD.d.ts @@ -6,7 +6,7 @@ type AggregateRoot> = { readonly id: ID; }; -type Repository, ID extends AggregateId = T["id"]> = { +type Repository, ID extends AggregateId = T['id']> = { getNextId(): Promise; store(entity: T): Promise; }; diff --git a/src/_lib/Environment.ts b/src/_lib/Environment.ts index 451a95c..ddfd7c3 100644 --- a/src/_lib/Environment.ts +++ b/src/_lib/Environment.ts @@ -1,16 +1,16 @@ -import dotenv from "dotenv"; -import { existsSync } from "fs"; +import dotenv from 'dotenv'; +import { existsSync } from 'fs'; dotenv.config({ path: - process.env.NODE_ENV === "production" - ? ".env" + process.env.NODE_ENV === 'production' + ? '.env' : existsSync(`.env.${process.env.NODE_ENV}.local`) ? `.env.${process.env.NODE_ENV}.local` : `.env.${process.env.NODE_ENV}`, }); -const environments = ["development", "production", "test"] as const; +const environments = ['development', 'production', 'test'] as const; type EnvironmentTypes = typeof environments[number]; @@ -18,7 +18,7 @@ type EnvironmentConfig = { environment: EnvironmentTypes; }; -const environment = (defaultValue: EnvironmentTypes = "development"): EnvironmentTypes => { +const environment = (defaultValue: EnvironmentTypes = 'development'): EnvironmentTypes => { let env: any = process.env.NODE_ENV; if (!env) { @@ -26,7 +26,7 @@ const environment = (defaultValue: EnvironmentTypes = "development"): Environmen } if (!environments.includes(env)) { - throw new TypeError(`Invalid value for NODE_ENV variable. Accepted values are: ${environments.join(" | ")}.`); + throw new TypeError(`Invalid value for NODE_ENV variable. Accepted values are: ${environments.join(' | ')}.`); } return env; diff --git a/src/_lib/IdProvider.ts b/src/_lib/IdProvider.ts index da09f55..5329fa4 100644 --- a/src/_lib/IdProvider.ts +++ b/src/_lib/IdProvider.ts @@ -1,12 +1,12 @@ -import { AggregateId } from "@/_lib/DDD"; +import { AggregateId } from '@/_lib/DDD'; -type IdProvider, N = T["value"]> = { +type IdProvider, N = T['value']> = { create(id: N): T; ensure(id: T): id is T; validate(id: T): void; }; -const makeIdProvider = , N = T["value"]>(idName: string): IdProvider => { +const makeIdProvider = , N = T['value']>(idName: string): IdProvider => { const key = Symbol(); return { diff --git a/src/_lib/MongoProvider.ts b/src/_lib/MongoProvider.ts index 3dc0fac..3901d55 100644 --- a/src/_lib/MongoProvider.ts +++ b/src/_lib/MongoProvider.ts @@ -1,7 +1,7 @@ -import { Collection, Db } from "mongodb"; -import MUUID from "uuid-mongodb"; +import { Collection, Db } from 'mongodb'; +import MUUID from 'uuid-mongodb'; -MUUID.mode("relaxed"); +MUUID.mode('relaxed'); interface Dependencies { db: Db; diff --git a/src/_lib/Predicate.ts b/src/_lib/Predicate.ts index e8928b8..f4e3f4d 100644 --- a/src/_lib/Predicate.ts +++ b/src/_lib/Predicate.ts @@ -1,5 +1,5 @@ const makePredicate = - (value: symbol | string | any, key: string | symbol = "type") => + (value: symbol | string | any, key: string | symbol = 'type') => (obj: T | any): obj is T => obj[key] === value; diff --git a/src/_lib/WithInvariants.ts b/src/_lib/WithInvariants.ts index 78d15a6..961b836 100644 --- a/src/_lib/WithInvariants.ts +++ b/src/_lib/WithInvariants.ts @@ -1,5 +1,5 @@ -import { AggregateRoot } from "@/_lib/DDD"; -import assertFn from "assert"; +import { AggregateRoot } from '@/_lib/DDD'; +import assertFn from 'assert'; type AssertionFn = (value: any, message?: string | Error) => void; diff --git a/src/_lib/di/containerAdapters.ts b/src/_lib/di/containerAdapters.ts index e56cd92..323aadf 100644 --- a/src/_lib/di/containerAdapters.ts +++ b/src/_lib/di/containerAdapters.ts @@ -1,5 +1,5 @@ -import { Resolver } from "awilix/lib/resolvers"; -import { asValue } from "awilix"; +import { Resolver } from 'awilix/lib/resolvers'; +import { asValue } from 'awilix'; type Values = Record; diff --git a/src/_lib/errors/BadRequestError.ts b/src/_lib/errors/BadRequestError.ts index 99699fd..49ae92a 100644 --- a/src/_lib/errors/BadRequestError.ts +++ b/src/_lib/errors/BadRequestError.ts @@ -1,9 +1,9 @@ -import { BaseError, Exception } from "@/_lib/errors/BaseError"; -import { makePredicate } from "@/_lib/Predicate"; +import { BaseError, Exception } from '@/_lib/errors/BaseError'; +import { makePredicate } from '@/_lib/Predicate'; namespace BadRequestError { const type = Symbol(); - const code = "BadRequestError"; + const code = 'BadRequestError'; export const create = (message: string): Exception => new BaseError({ type, code, message }); diff --git a/src/_lib/errors/ForbiddenError.ts b/src/_lib/errors/ForbiddenError.ts index afc9012..47e1333 100644 --- a/src/_lib/errors/ForbiddenError.ts +++ b/src/_lib/errors/ForbiddenError.ts @@ -1,10 +1,10 @@ -import { BaseError, Exception } from "@/_lib/errors/BaseError"; -import { makePredicate } from "@/_lib/Predicate"; +import { BaseError, Exception } from '@/_lib/errors/BaseError'; +import { makePredicate } from '@/_lib/Predicate'; namespace ForbiddenError { const type = Symbol(); - const code = "ForbiddenError"; - const message = "Forbidden"; + const code = 'ForbiddenError'; + const message = 'Forbidden'; export const create = (customMsg?: string): Exception => new BaseError({ type, code, message: customMsg || message }); diff --git a/src/_lib/errors/NotFoundError.ts b/src/_lib/errors/NotFoundError.ts index d911970..d1b83a8 100644 --- a/src/_lib/errors/NotFoundError.ts +++ b/src/_lib/errors/NotFoundError.ts @@ -1,9 +1,9 @@ -import { BaseError, Exception } from "@/_lib/errors/BaseError"; -import { makePredicate } from "@/_lib/Predicate"; +import { BaseError, Exception } from '@/_lib/errors/BaseError'; +import { makePredicate } from '@/_lib/Predicate'; namespace NotFoundError { const type = Symbol(); - const code = "NotFoundError"; + const code = 'NotFoundError'; export const create = (message: string): Exception => new BaseError({ type, code, message }); diff --git a/src/_lib/errors/UnauthorizedError.ts b/src/_lib/errors/UnauthorizedError.ts index 58c304a..0e0e5da 100644 --- a/src/_lib/errors/UnauthorizedError.ts +++ b/src/_lib/errors/UnauthorizedError.ts @@ -1,10 +1,10 @@ -import { BaseError, Exception } from "@/_lib/errors/BaseError"; -import { makePredicate } from "@/_lib/Predicate"; +import { BaseError, Exception } from '@/_lib/errors/BaseError'; +import { makePredicate } from '@/_lib/Predicate'; namespace UnauthorizedError { const type = Symbol(); - const code = "UnauthorizedError"; - const message = "Unauthorized"; + const code = 'UnauthorizedError'; + const message = 'Unauthorized'; export const create = (customMsg?: string): Exception => new BaseError({ type, code, message: customMsg || message }); diff --git a/src/_lib/errors/ValidationError.ts b/src/_lib/errors/ValidationError.ts index 9acbbee..6b84a90 100644 --- a/src/_lib/errors/ValidationError.ts +++ b/src/_lib/errors/ValidationError.ts @@ -1,10 +1,10 @@ -import Joi from "types-joi"; -import { BaseError, Exception } from "@/_lib/errors/BaseError"; -import { makePredicate } from "@/_lib/Predicate"; +import Joi from 'types-joi'; +import { BaseError, Exception } from '@/_lib/errors/BaseError'; +import { makePredicate } from '@/_lib/Predicate'; namespace ValidationError { const type = Symbol(); - const code = "ValidationError"; + const code = 'ValidationError'; type Props = { readonly target: string; diff --git a/src/_lib/events/EventConsumer.ts b/src/_lib/events/EventConsumer.ts index ccca735..e2a3e70 100644 --- a/src/_lib/events/EventConsumer.ts +++ b/src/_lib/events/EventConsumer.ts @@ -1,10 +1,10 @@ -import { Event, EventAddress } from "@/_lib/events/Event"; -import { Subscriber, SubscriberOptions } from "@/_lib/events/Subscriber"; +import { Event, EventAddress } from '@/_lib/events/Event'; +import { Subscriber, SubscriberOptions } from '@/_lib/events/Subscriber'; const makeEventConsumer = - (subscriberKey: S = "subscriber" as S) => + (subscriberKey: S = 'subscriber' as S) => , D extends Record | void = void, OPTS = SubscriberOptions>( - address: EventAddress, + address: EventAddress, fn: (deps: D) => (event: E) => Promise, opts: Partial = {} ) => diff --git a/src/_lib/events/EventProvider.ts b/src/_lib/events/EventProvider.ts index e84060f..2ec55f6 100644 --- a/src/_lib/events/EventProvider.ts +++ b/src/_lib/events/EventProvider.ts @@ -1,6 +1,6 @@ -import { ApplicationService } from "@/_lib/DDD"; -import { Event } from "@/_lib/events/Event"; -import { Publisher } from "@/_lib/events/Publisher"; +import { ApplicationService } from '@/_lib/DDD'; +import { Event } from '@/_lib/events/Event'; +import { Publisher } from '@/_lib/events/Publisher'; type Enqueue = >(event: E) => void; @@ -10,7 +10,7 @@ type EventStore = { }; const makeEventProvider = - (publisherKey: S = "publisher" as S) => + (publisherKey: S = 'publisher' as S) => , AS extends ApplicationService>(fn: (deps: D, enqueue: Enqueue) => AS) => (deps: D & { [key in S]: Publisher }): AS => { const { [publisherKey]: publisher } = deps; diff --git a/src/_lib/events/Publisher.d.ts b/src/_lib/events/Publisher.d.ts index 80b2c77..6176e55 100644 --- a/src/_lib/events/Publisher.d.ts +++ b/src/_lib/events/Publisher.d.ts @@ -1,4 +1,4 @@ -import { Event } from "@/_lib/events/Event"; +import { Event } from '@/_lib/events/Event'; type Publisher = { publish: >(event: T) => Promise; diff --git a/src/_lib/events/Subscriber.d.ts b/src/_lib/events/Subscriber.d.ts index 25b4499..ac3e814 100644 --- a/src/_lib/events/Subscriber.d.ts +++ b/src/_lib/events/Subscriber.d.ts @@ -1,4 +1,4 @@ -import { Event, EventAddress } from "@/_lib/events/Event"; +import { Event, EventAddress } from '@/_lib/events/Event'; type SubscriberOptions = { single: boolean; @@ -7,7 +7,7 @@ type SubscriberOptions = { type Subscriber = { add: >( - address: EventAddress, + address: EventAddress, handler: (event: E) => Promise, opts?: Partial ) => Promise; diff --git a/src/_lib/http/handler.ts b/src/_lib/http/handler.ts index 66a6e3e..b3ee92c 100644 --- a/src/_lib/http/handler.ts +++ b/src/_lib/http/handler.ts @@ -1,6 +1,6 @@ -import { RequestHandler } from "express"; -import { asFunction } from "awilix"; -import { AsyncHandler, runAsync } from "@/_lib/http/runAsync"; +import { RequestHandler } from 'express'; +import { asFunction } from 'awilix'; +import { AsyncHandler, runAsync } from '@/_lib/http/runAsync'; type ControllerHandler = (dependencies: any) => AsyncHandler; @@ -8,7 +8,7 @@ const handler = (handler: ControllerHandler): RequestHandler => { const resolver = asFunction(handler); return (req, res, next) => { - if (!("container" in req)) { + if (!('container' in req)) { throw new Error("Can't find the request container! Have you registered the `requestContainer` middleware?"); } diff --git a/src/_lib/http/middlewares/errorHandler.ts b/src/_lib/http/middlewares/errorHandler.ts index 282f375..d7ceaeb 100644 --- a/src/_lib/http/middlewares/errorHandler.ts +++ b/src/_lib/http/middlewares/errorHandler.ts @@ -1,5 +1,5 @@ -import { ErrorRequestHandler } from "express"; -import { Exception } from "@/_lib/errors/BaseError"; +import { ErrorRequestHandler } from 'express'; +import { Exception } from '@/_lib/errors/BaseError'; type ErrorConverter = { test: (err: E | any) => err is E; @@ -20,7 +20,7 @@ const makeErrorResponseBuilder = (errorConverters: ErrorConverter[]) => (er }; type ErrorHandlerOptions = { - logger: Pick; + logger: Pick; }; const defaultOptions: ErrorHandlerOptions = { @@ -42,7 +42,7 @@ const errorHandler = ( if (errorResponse) { const { status, body } = errorResponse; - return res.status(status).json(typeof body === "object" ? body : { error: body }); + return res.status(status).json(typeof body === 'object' ? body : { error: body }); } res.status(500).json({ error: err.message }); diff --git a/src/_lib/http/middlewares/gracefulShutdown.ts b/src/_lib/http/middlewares/gracefulShutdown.ts index 5faa720..0e7c8fd 100644 --- a/src/_lib/http/middlewares/gracefulShutdown.ts +++ b/src/_lib/http/middlewares/gracefulShutdown.ts @@ -1,6 +1,6 @@ -import { Server } from "http"; -import { logger } from "@/_lib/logger"; -import { RequestHandler } from "express"; +import { Server } from 'http'; +import { logger } from '@/_lib/logger'; +import { RequestHandler } from 'express'; type ShutdownMiddleware = { shutdownHook: () => Promise; @@ -18,17 +18,17 @@ const gracefulShutdown = (server: Server, forceTimeout = 30000): ShutdownMiddlew shuttingDown = true; - logger.warn("Shutting down server"); + logger.warn('Shutting down server'); setTimeout(() => { - logger.error("Could not close connections in time, forcefully shutting down"); + logger.error('Could not close connections in time, forcefully shutting down'); resolve(); }, forceTimeout).unref(); server.close((err) => { if (err) return reject(err); - logger.info("Closed out remaining connections."); + logger.info('Closed out remaining connections.'); resolve(); }); }); @@ -39,8 +39,8 @@ const gracefulShutdown = (server: Server, forceTimeout = 30000): ShutdownMiddlew return next(); } - res.set("Connection", "close"); - res.status(503).send("Server is in the process of restarting."); + res.set('Connection', 'close'); + res.status(503).send('Server is in the process of restarting.'); }, shutdownHook, }; diff --git a/src/_lib/http/middlewares/requestContainer.ts b/src/_lib/http/middlewares/requestContainer.ts index 56b72c0..a3b16a4 100644 --- a/src/_lib/http/middlewares/requestContainer.ts +++ b/src/_lib/http/middlewares/requestContainer.ts @@ -1,6 +1,6 @@ -import { asValue } from "awilix"; -import { RequestHandler } from "express"; -import { Container } from "@/container"; +import { asValue } from 'awilix'; +import { RequestHandler } from 'express'; +import { Container } from '@/container'; const requestContainer = (container: Container): RequestHandler => diff --git a/src/_lib/http/middlewares/requestId.ts b/src/_lib/http/middlewares/requestId.ts index cb70245..195cc97 100644 --- a/src/_lib/http/middlewares/requestId.ts +++ b/src/_lib/http/middlewares/requestId.ts @@ -1,5 +1,5 @@ -import { v4 } from "uuid"; -import { RequestHandler } from "express"; +import { v4 } from 'uuid'; +import { RequestHandler } from 'express'; const requestId = (idProvider: () => string = v4): RequestHandler => diff --git a/src/_lib/http/runAsync.ts b/src/_lib/http/runAsync.ts index 53a7453..87d02c4 100644 --- a/src/_lib/http/runAsync.ts +++ b/src/_lib/http/runAsync.ts @@ -1,4 +1,4 @@ -import { NextFunction, Request, Response } from "express"; +import { NextFunction, Request, Response } from 'express'; type AsyncHandler = (req: Request, res: Response, next: NextFunction) => Promise; diff --git a/src/_lib/http/validation/Paginator.ts b/src/_lib/http/validation/Paginator.ts index 402fc8e..2b02a15 100644 --- a/src/_lib/http/validation/Paginator.ts +++ b/src/_lib/http/validation/Paginator.ts @@ -1,11 +1,11 @@ -import { Request } from "express"; -import Joi, { InterfaceFrom } from "types-joi"; -import { ValidationError } from "@/_lib/errors/ValidationError"; -import { BadRequestError } from "@/_lib/errors/BadRequestError"; +import { Request } from 'express'; +import Joi, { InterfaceFrom } from 'types-joi'; +import { ValidationError } from '@/_lib/errors/ValidationError'; +import { BadRequestError } from '@/_lib/errors/BadRequestError'; type FieldConfig = { name: string; - from: "query" | "params" | "body"; + from: 'query' | 'params' | 'body'; }; type PaginatorOptions> = { @@ -19,10 +19,10 @@ type PaginatorOptions> = { defaults?: { pageSize?: number; page?: number; - filter?: T["filter"] extends Joi.BaseSchema ? NonNullable>> : any; + filter?: T['filter'] extends Joi.BaseSchema ? NonNullable>> : any; sort?: { field: string; - direction: "asc" | "desc"; + direction: 'asc' | 'desc'; }[]; }; filter?: Joi.BaseSchema | null; @@ -32,17 +32,17 @@ type Paginator>> = { getPagination: (req: Request) => { page: number; pageSize: number }; getFilter: ( req: Request - ) => T["filter"] extends Joi.BaseSchema ? NonNullable>> : any; - getSorter: (req: Request) => { field: string; direction: "asc" | "desc" }[]; + ) => T['filter'] extends Joi.BaseSchema ? NonNullable>> : any; + getSorter: (req: Request) => { field: string; direction: 'asc' | 'desc' }[]; }; const defaultOptions = { useDefaults: true, fields: { - page: "page", - pageSize: "limit", - sort: "sort", - filter: "filter", + page: 'page', + pageSize: 'limit', + sort: 'sort', + filter: 'filter', }, defaults: { page: 1, @@ -68,7 +68,7 @@ const makePaginator = >(opts: Partial = {}): }; const getField = (field: string | FieldConfig): FieldConfig => - typeof field === "string" ? { name: field, from: "query" } : field; + typeof field === 'string' ? { name: field, from: 'query' } : field; const fromRequest = (req: Request, field: FieldConfig) => req[field.from][field.name]; @@ -91,7 +91,7 @@ const makePaginator = >(opts: Partial = {}): }; }; - const getSorter = (req: Request): { field: string; direction: "asc" | "desc" }[] => { + const getSorter = (req: Request): { field: string; direction: 'asc' | 'desc' }[] => { const sortField = getField(fields.sort); const sortValues = fromRequest(req, sortField); @@ -103,15 +103,15 @@ const makePaginator = >(opts: Partial = {}): return sortList.length ? sortList.map((sort) => ({ - field: sort.startsWith("-") ? sort.substr(1) : sort, - direction: sort.startsWith("-") ? "desc" : "asc", + field: sort.startsWith('-') ? sort.substr(1) : sort, + direction: sort.startsWith('-') ? 'desc' : 'asc', })) : defaults.sort; }; const getFilter = ( req: Request - ): T["filter"] extends Joi.BaseSchema ? NonNullable>> : any => { + ): T['filter'] extends Joi.BaseSchema ? NonNullable>> : any => { const filterField = getField(fields.filter); const filterValue = fromRequest(req, filterField); diff --git a/src/_lib/http/validation/Validator.ts b/src/_lib/http/validation/Validator.ts index f5e9bf6..fcfb6ee 100644 --- a/src/_lib/http/validation/Validator.ts +++ b/src/_lib/http/validation/Validator.ts @@ -1,7 +1,7 @@ -import * as Joi from "types-joi"; -import { Request } from "express"; -import { InterfaceFrom } from "types-joi"; -import { ValidationError } from "@/_lib/errors/ValidationError"; +import * as Joi from 'types-joi'; +import { Request } from 'express'; +import { InterfaceFrom } from 'types-joi'; +import { ValidationError } from '@/_lib/errors/ValidationError'; type ValidationSchemas = { body?: Joi.BaseSchema; @@ -14,11 +14,11 @@ type ValidationSchemas = { type ValidationType = T extends Joi.BaseSchema ? InterfaceFrom> : any; type ValidationHelpers = { - getBody(req: Request): ValidationType; - getParams(req: Request): ValidationType; - getQuery(req: Request): ValidationType; - getCookies(req: Request): ValidationType; - getHeaders(req: Request): ValidationType; + getBody(req: Request): ValidationType; + getParams(req: Request): ValidationType; + getQuery(req: Request): ValidationType; + getCookies(req: Request): ValidationType; + getHeaders(req: Request): ValidationType; }; const makeValidator = (schemas: T): ValidationHelpers => { @@ -37,11 +37,11 @@ const makeValidator = (schemas: T): ValidationHelpe }; return { - getBody: createValidator("body"), - getParams: createValidator("params"), - getQuery: createValidator("query"), - getHeaders: createValidator("headers"), - getCookies: createValidator("cookies"), + getBody: createValidator('body'), + getParams: createValidator('params'), + getQuery: createValidator('query'), + getHeaders: createValidator('headers'), + getCookies: createValidator('cookies'), }; }; diff --git a/src/_lib/logger/index.ts b/src/_lib/logger/index.ts index 6d48e26..f9a128d 100644 --- a/src/_lib/logger/index.ts +++ b/src/_lib/logger/index.ts @@ -1,4 +1,4 @@ -import pino from "pino"; +import pino from 'pino'; const logger = pino(); diff --git a/src/_lib/message/MessageBundle.ts b/src/_lib/message/MessageBundle.ts index 0547989..3dba28c 100644 --- a/src/_lib/message/MessageBundle.ts +++ b/src/_lib/message/MessageBundle.ts @@ -1,4 +1,4 @@ -import _ from "lodash"; +import _ from 'lodash'; _.templateSettings.interpolate = /{{([\s\S]+?)}}/g; @@ -16,7 +16,7 @@ type MessageSource = { : string; }; -type None = ["no", "arguements"]; +type None = ['no', 'arguements']; type JoinParameters = T extends [] ? never @@ -54,7 +54,7 @@ type DeepPartial = { type UnionToIntersection = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never; -type FlattenParameters = UnionToIntersection, ".">>; +type FlattenParameters = UnionToIntersection, '.'>>; type TuplefyKeys = T extends string ? [] @@ -72,7 +72,7 @@ type DotNotation = T extends [] : never : string; -type FlattenMessageSource> = Record, ".">, string>; +type FlattenMessageSource> = Record, '.'>, string>; type MessageBundle = { getMessage: >( @@ -88,11 +88,11 @@ type MessageBundle = { ) => { message: string; template: string | null; key: K; parameters?: FlattenParameters[K] }; }; -const flatten = (object: Record, prevKey = ""): Record => +const flatten = (object: Record, prevKey = ''): Record => Object.entries(object).reduce( (acc, [key, item]) => ({ ...acc, - ...(typeof item === "object" + ...(typeof item === 'object' ? flatten(item, prevKey ? `${prevKey}.${key}` : key) : { [prevKey ? `${prevKey}.${key}` : key]: item }), }), @@ -125,7 +125,7 @@ const makeMessegeBundle = ( const message = compiledBundle[key]; if (!message) { - return ""; + return ''; } return message(...parameters); diff --git a/src/_lib/pubSub/EventEmitterConsumer.ts b/src/_lib/pubSub/EventEmitterConsumer.ts index 0823c54..44be621 100644 --- a/src/_lib/pubSub/EventEmitterConsumer.ts +++ b/src/_lib/pubSub/EventEmitterConsumer.ts @@ -1,5 +1,5 @@ -import { makeEventConsumer } from "@/_lib/events/EventConsumer"; -import { key } from "@/_lib/pubSub/EventEmitterPubSub"; +import { makeEventConsumer } from '@/_lib/events/EventConsumer'; +import { key } from '@/_lib/pubSub/EventEmitterPubSub'; const eventConsumer = makeEventConsumer(key); diff --git a/src/_lib/pubSub/EventEmitterProvider.ts b/src/_lib/pubSub/EventEmitterProvider.ts index 5034d37..fceffae 100644 --- a/src/_lib/pubSub/EventEmitterProvider.ts +++ b/src/_lib/pubSub/EventEmitterProvider.ts @@ -1,5 +1,5 @@ -import { makeEventProvider } from "@/_lib/events/EventProvider"; -import { key } from "@/_lib/pubSub/EventEmitterPubSub"; +import { makeEventProvider } from '@/_lib/events/EventProvider'; +import { key } from '@/_lib/pubSub/EventEmitterPubSub'; const eventProvider = makeEventProvider(key); diff --git a/src/_lib/pubSub/EventEmitterPubSub.ts b/src/_lib/pubSub/EventEmitterPubSub.ts index 6e90a33..4d21aad 100644 --- a/src/_lib/pubSub/EventEmitterPubSub.ts +++ b/src/_lib/pubSub/EventEmitterPubSub.ts @@ -1,6 +1,6 @@ -import { Publisher } from "@/_lib/events/Publisher"; -import { Subscriber, SubscriberOptions } from "@/_lib/events/Subscriber"; -import { EventEmitter } from "stream"; +import { Publisher } from '@/_lib/events/Publisher'; +import { Subscriber, SubscriberOptions } from '@/_lib/events/Subscriber'; +import { EventEmitter } from 'stream'; const defaultOpts: SubscriberOptions = { nackOn: () => true, @@ -20,7 +20,7 @@ const makeEventEmitterPubSub = (): Publisher & Subscriber => { const { single, nackOn } = { ...defaultOpts, ...opts }; registrations.push(async () => { - emitter[single ? "once" : "on"](`${address.topic}.${address.eventType}`, async (event) => { + emitter[single ? 'once' : 'on'](`${address.topic}.${address.eventType}`, async (event) => { try { await handler(event); } catch (err) { @@ -42,6 +42,6 @@ const makeEventEmitterPubSub = (): Publisher & Subscriber => { }; }; -const key = "eventEmitterPubSub"; +const key = 'eventEmitterPubSub'; export { key, makeEventEmitterPubSub }; diff --git a/src/_sharedKernel/domain/ArticleId.d.ts b/src/_sharedKernel/domain/ArticleId.d.ts index 4048e25..bb388c0 100644 --- a/src/_sharedKernel/domain/ArticleId.d.ts +++ b/src/_sharedKernel/domain/ArticleId.d.ts @@ -1,4 +1,4 @@ -import { AggregateId } from "@/_lib/DDD"; +import { AggregateId } from '@/_lib/DDD'; type ArticleId = AggregateId; diff --git a/src/_sharedKernel/domain/error/BusinessError.ts b/src/_sharedKernel/domain/error/BusinessError.ts index 44f5a16..16451e2 100644 --- a/src/_sharedKernel/domain/error/BusinessError.ts +++ b/src/_sharedKernel/domain/error/BusinessError.ts @@ -1,9 +1,9 @@ -import { BaseError, Exception } from "@/_lib/errors/BaseError"; -import { makePredicate } from "@/_lib/Predicate"; +import { BaseError, Exception } from '@/_lib/errors/BaseError'; +import { makePredicate } from '@/_lib/Predicate'; namespace BusinessError { const type = Symbol(); - const code = "BusinessError"; + const code = 'BusinessError'; type Props = { key: string; diff --git a/src/_sharedKernel/infrastructure/ArticleIdProvider.ts b/src/_sharedKernel/infrastructure/ArticleIdProvider.ts index 73f4316..769a139 100644 --- a/src/_sharedKernel/infrastructure/ArticleIdProvider.ts +++ b/src/_sharedKernel/infrastructure/ArticleIdProvider.ts @@ -1,6 +1,6 @@ -import { makeIdProvider } from "@/_lib/IdProvider"; -import { ArticleId } from "@/_sharedKernel/domain/ArticleId"; +import { makeIdProvider } from '@/_lib/IdProvider'; +import { ArticleId } from '@/_sharedKernel/domain/ArticleId'; -const ArticleIdProvider = makeIdProvider("ArticleId"); +const ArticleIdProvider = makeIdProvider('ArticleId'); export { ArticleIdProvider }; diff --git a/src/_sharedKernel/infrastructure/MemoryDB.ts b/src/_sharedKernel/infrastructure/MemoryDB.ts index 35f80ab..801770e 100644 --- a/src/_sharedKernel/infrastructure/MemoryDB.ts +++ b/src/_sharedKernel/infrastructure/MemoryDB.ts @@ -1,5 +1,5 @@ -import { Article } from "@/article/domain/Article"; -import { Comment } from "@/comment/domain/Comment"; +import { Article } from '@/article/domain/Article'; +import { Comment } from '@/comment/domain/Comment'; type MemoryDB = { articles: Record; diff --git a/src/_sharedKernel/interface/http/ErrorConverters.ts b/src/_sharedKernel/interface/http/ErrorConverters.ts index a400edf..f5519c1 100644 --- a/src/_sharedKernel/interface/http/ErrorConverters.ts +++ b/src/_sharedKernel/interface/http/ErrorConverters.ts @@ -1,16 +1,16 @@ -import { ValidationError } from "@/_lib/errors/ValidationError"; -import { errorConverter } from "@/_lib/http/middlewares/errorHandler"; -import { BaseError } from "@/_lib/errors/BaseError"; -import { NotFoundError } from "@/_lib/errors/NotFoundError"; -import { HttpStatus } from "@/_lib/http/HttpStatus"; -import { UnauthorizedError } from "@/_lib/errors/UnauthorizedError"; -import { ForbiddenError } from "@/_lib/errors/ForbiddenError"; -import { BusinessError } from "@/_sharedKernel/domain/error/BusinessError"; -import { BadRequestError } from "@/_lib/errors/BadRequestError"; +import { ValidationError } from '@/_lib/errors/ValidationError'; +import { errorConverter } from '@/_lib/http/middlewares/errorHandler'; +import { BaseError } from '@/_lib/errors/BaseError'; +import { NotFoundError } from '@/_lib/errors/NotFoundError'; +import { HttpStatus } from '@/_lib/http/HttpStatus'; +import { UnauthorizedError } from '@/_lib/errors/UnauthorizedError'; +import { ForbiddenError } from '@/_lib/errors/ForbiddenError'; +import { BusinessError } from '@/_sharedKernel/domain/error/BusinessError'; +import { BadRequestError } from '@/_lib/errors/BadRequestError'; const errorConverters = [ errorConverter(ValidationError.is, (err) => { - const status = err.meta?.target === "body" ? HttpStatus.UNPROCESSABLE_ENTITY : HttpStatus.BAD_REQUEST; + const status = err.meta?.target === 'body' ? HttpStatus.UNPROCESSABLE_ENTITY : HttpStatus.BAD_REQUEST; return { status, @@ -19,7 +19,7 @@ const errorConverters = [ status, message: err.message, details: err.meta?.error.details.map((detail) => ({ - field: detail.path.join("."), + field: detail.path.join('.'), path: detail.path, })), }, diff --git a/src/article/__tests__/integration/interface/http/ArticleController.spec.ts b/src/article/__tests__/integration/interface/http/ArticleController.spec.ts index 63d4576..14786c8 100644 --- a/src/article/__tests__/integration/interface/http/ArticleController.spec.ts +++ b/src/article/__tests__/integration/interface/http/ArticleController.spec.ts @@ -1,7 +1,7 @@ -import { randomBytes } from "crypto"; -import { makeTestControls, TestControls } from "@/__tests__/TestControls"; +import { randomBytes } from 'crypto'; +import { makeTestControls, TestControls } from '@/__tests__/TestControls'; -describe("ArticleController", () => { +describe('ArticleController', () => { let controls: TestControls; beforeAll(async () => { @@ -20,25 +20,25 @@ describe("ArticleController", () => { await cleanUp(); }); - describe("POST /api/articles", () => { - it("should create a new Article", async () => { + describe('POST /api/articles', () => { + it('should create a new Article', async () => { const { request, registry: { articleRepository }, } = controls; - const title = randomBytes(20).toString("hex"); - const content = "New Article content"; + const title = randomBytes(20).toString('hex'); + const content = 'New Article content'; return request() - .post("/api/articles") + .post('/api/articles') .send({ title, content, }) .expect(async (res) => { expect(res.status).toBe(201); - expect(res.body).toHaveProperty("id"); + expect(res.body).toHaveProperty('id'); const article = await articleRepository.findById(res.body.id); @@ -51,26 +51,26 @@ describe("ArticleController", () => { }); }); - it("should fail with 422 when no title is present", async () => { + it('should fail with 422 when no title is present', async () => { const { request } = controls; return request() - .post("/api/articles") + .post('/api/articles') .send({ - content: "New Article content", + content: 'New Article content', }) .expect((res) => { expect(res.status).toBe(422); }); }); - it("should fail with 422 when no content is present", async () => { + it('should fail with 422 when no content is present', async () => { const { request } = controls; return request() - .post("/api/articles") + .post('/api/articles') .send({ - title: randomBytes(20).toString("hex"), + title: randomBytes(20).toString('hex'), }) .expect((res) => { expect(res.status).toBe(422); diff --git a/src/article/__tests__/unit/application/CreateArticle.test.ts b/src/article/__tests__/unit/application/CreateArticle.test.ts index 852eb46..a143ac0 100644 --- a/src/article/__tests__/unit/application/CreateArticle.test.ts +++ b/src/article/__tests__/unit/application/CreateArticle.test.ts @@ -1,12 +1,12 @@ -import { ArticleCreatedEvent } from "@/article/application/events/ArticleCreatedEvent"; -import { CreateArticle, makeCreateArticle } from "@/article/application/useCases/CreateArticle"; -import { ArticleRepository } from "@/article/domain/ArticleRepository"; -import { Publisher } from "@/_lib/events/Publisher"; +import { ArticleCreatedEvent } from '@/article/application/events/ArticleCreatedEvent'; +import { CreateArticle, makeCreateArticle } from '@/article/application/useCases/CreateArticle'; +import { ArticleRepository } from '@/article/domain/ArticleRepository'; +import { Publisher } from '@/_lib/events/Publisher'; -describe("CreateArticle", () => { - const id = "mock-article-id"; - const title = "Title"; - const content = "Some content"; +describe('CreateArticle', () => { + const id = 'mock-article-id'; + const title = 'Title'; + const content = 'Some content'; const articleRepository: ArticleRepository = { findById: jest.fn(), @@ -25,13 +25,13 @@ describe("CreateArticle", () => { createArticle = makeCreateArticle({ articleRepository, eventEmitterPubSub: publisher }); }); - it("should return the created id", async () => { + it('should return the created id', async () => { const result = await createArticle({ title, content }); expect(result).toBe(id); }); - it("should store the article", async () => { + it('should store the article', async () => { await createArticle({ title, content }); expect(articleRepository.store).toHaveBeenCalledWith( @@ -43,7 +43,7 @@ describe("CreateArticle", () => { ); }); - it("should enqueue ArticleCreatedEvent", async () => { + it('should enqueue ArticleCreatedEvent', async () => { await createArticle({ title, content }); expect(publisher.publish).toHaveBeenCalledWith( diff --git a/src/article/__tests__/unit/application/DeleteArticle.test.ts b/src/article/__tests__/unit/application/DeleteArticle.test.ts index 016534e..c8200ba 100644 --- a/src/article/__tests__/unit/application/DeleteArticle.test.ts +++ b/src/article/__tests__/unit/application/DeleteArticle.test.ts @@ -1,13 +1,13 @@ -import { DeleteArticle, makeDeleteArticle } from "@/article/application/useCases/DeleteArticle"; -import { Article } from "@/article/domain/Article"; -import { ArticleRepository } from "@/article/domain/ArticleRepository"; -import { BaseError } from "@/_lib/errors/BaseError"; -import { NotFoundError } from "@/_lib/errors/NotFoundError"; +import { DeleteArticle, makeDeleteArticle } from '@/article/application/useCases/DeleteArticle'; +import { Article } from '@/article/domain/Article'; +import { ArticleRepository } from '@/article/domain/ArticleRepository'; +import { BaseError } from '@/_lib/errors/BaseError'; +import { NotFoundError } from '@/_lib/errors/NotFoundError'; -describe("DeleteArticle", () => { - const id = "mock-article-id"; - const title = "Title"; - const content = "Some content"; +describe('DeleteArticle', () => { + const id = 'mock-article-id'; + const title = 'Title'; + const content = 'Some content'; const articleRepository: ArticleRepository = { findById: jest.fn().mockImplementation(async (articleId) => { @@ -32,18 +32,18 @@ describe("DeleteArticle", () => { deleteArticle = makeDeleteArticle({ articleRepository }); }); - it("should save the article as deleted", async () => { + it('should save the article as deleted', async () => { await deleteArticle(id); expect(articleRepository.store).toHaveBeenCalledWith( expect.objectContaining({ id: { value: id }, - state: "DELETED", + state: 'DELETED', }) ); }); - it("should throw error if not found", async () => { - await expect(deleteArticle("some-wrong-id")).rejects.toThrowError(BaseError); + it('should throw error if not found', async () => { + await expect(deleteArticle('some-wrong-id')).rejects.toThrowError(BaseError); }); }); diff --git a/src/article/__tests__/unit/application/PublishArticle.test.ts b/src/article/__tests__/unit/application/PublishArticle.test.ts index e413304..324b809 100644 --- a/src/article/__tests__/unit/application/PublishArticle.test.ts +++ b/src/article/__tests__/unit/application/PublishArticle.test.ts @@ -1,14 +1,14 @@ -import { makePublishArticle, PublishArticle } from "@/article/application/useCases/PublishArticle"; -import { Article } from "@/article/domain/Article"; -import { ArticleRepository } from "@/article/domain/ArticleRepository"; -import { BaseError } from "@/_lib/errors/BaseError"; -import { NotFoundError } from "@/_lib/errors/NotFoundError"; -import pino from "pino"; - -describe("DeleteArticle", () => { - const id = "mock-article-id"; - const title = "Title"; - const content = "Some content"; +import { makePublishArticle, PublishArticle } from '@/article/application/useCases/PublishArticle'; +import { Article } from '@/article/domain/Article'; +import { ArticleRepository } from '@/article/domain/ArticleRepository'; +import { BaseError } from '@/_lib/errors/BaseError'; +import { NotFoundError } from '@/_lib/errors/NotFoundError'; +import pino from 'pino'; + +describe('DeleteArticle', () => { + const id = 'mock-article-id'; + const title = 'Title'; + const content = 'Some content'; const articleRepository: ArticleRepository = { findById: jest.fn().mockImplementation(async (articleId) => { @@ -37,18 +37,18 @@ describe("DeleteArticle", () => { }); }); - it("should save the article as published", async () => { + it('should save the article as published', async () => { await publishArticle(id); expect(articleRepository.store).toHaveBeenCalledWith( expect.objectContaining({ id: { value: id }, - state: "PUBLISHED", + state: 'PUBLISHED', }) ); }); - it("should throw error if not found", async () => { - await expect(publishArticle("some-wrong-id")).rejects.toThrowError(BaseError); + it('should throw error if not found', async () => { + await expect(publishArticle('some-wrong-id')).rejects.toThrowError(BaseError); }); }); diff --git a/src/article/application/events/ArticleCreatedEvent.ts b/src/article/application/events/ArticleCreatedEvent.ts index 0e18ef4..2cecdaf 100644 --- a/src/article/application/events/ArticleCreatedEvent.ts +++ b/src/article/application/events/ArticleCreatedEvent.ts @@ -1,10 +1,10 @@ -import { Article } from "@/article/domain/Article"; -import { Event } from "@/_lib/events/Event"; -import { v4 } from "uuid-mongodb"; +import { Article } from '@/article/domain/Article'; +import { Event } from '@/_lib/events/Event'; +import { v4 } from 'uuid-mongodb'; namespace ArticleCreatedEvent { - export const topic = "Article" as const; - export const eventType = "ArticleCreatedEvent" as const; + export const topic = 'Article' as const; + export const eventType = 'ArticleCreatedEvent' as const; type ArticleCreatedEvent = Event; diff --git a/src/article/application/useCases/CreateArticle.ts b/src/article/application/useCases/CreateArticle.ts index 131ebda..4d09caf 100644 --- a/src/article/application/useCases/CreateArticle.ts +++ b/src/article/application/useCases/CreateArticle.ts @@ -1,8 +1,8 @@ -import { ArticleRepository } from "@/article/domain/ArticleRepository"; -import { Article } from "@/article/domain/Article"; -import { ApplicationService } from "@/_lib/DDD"; -import { ArticleCreatedEvent } from "@/article/application/events/ArticleCreatedEvent"; -import { eventProvider } from "@/_lib/pubSub/EventEmitterProvider"; +import { ArticleRepository } from '@/article/domain/ArticleRepository'; +import { Article } from '@/article/domain/Article'; +import { ApplicationService } from '@/_lib/DDD'; +import { ArticleCreatedEvent } from '@/article/application/events/ArticleCreatedEvent'; +import { eventProvider } from '@/_lib/pubSub/EventEmitterProvider'; type Dependencies = { articleRepository: ArticleRepository; diff --git a/src/article/application/useCases/DeleteArticle.ts b/src/article/application/useCases/DeleteArticle.ts index 592ffbd..4cae1bc 100644 --- a/src/article/application/useCases/DeleteArticle.ts +++ b/src/article/application/useCases/DeleteArticle.ts @@ -1,6 +1,6 @@ -import { ArticleRepository } from "@/article/domain/ArticleRepository"; -import { Article } from "@/article/domain/Article"; -import { ApplicationService } from "@/_lib/DDD"; +import { ArticleRepository } from '@/article/domain/ArticleRepository'; +import { Article } from '@/article/domain/Article'; +import { ApplicationService } from '@/_lib/DDD'; type Dependencies = { articleRepository: ArticleRepository; diff --git a/src/article/application/useCases/PublishArticle.ts b/src/article/application/useCases/PublishArticle.ts index f64fe83..ac430cb 100644 --- a/src/article/application/useCases/PublishArticle.ts +++ b/src/article/application/useCases/PublishArticle.ts @@ -1,9 +1,9 @@ -import { ArticleRepository } from "@/article/domain/ArticleRepository"; -import { Article } from "@/article/domain/Article"; -import { ApplicationService } from "@/_lib/DDD"; -import { BusinessError } from "@/_sharedKernel/domain/error/BusinessError"; -import { MessageBundle } from "@/messages"; -import { Logger } from "pino"; +import { ArticleRepository } from '@/article/domain/ArticleRepository'; +import { Article } from '@/article/domain/Article'; +import { ApplicationService } from '@/_lib/DDD'; +import { BusinessError } from '@/_sharedKernel/domain/error/BusinessError'; +import { MessageBundle } from '@/messages'; +import { Logger } from 'pino'; type Dependencies = { articleRepository: ArticleRepository; @@ -20,7 +20,7 @@ const makePublishArticle = if (Article.isPublished(article)) { throw BusinessError.create( - useBundle("article.error.alreadyPublished", { id: payload, publishedAt: article.publishedAt }) + useBundle('article.error.alreadyPublished', { id: payload, publishedAt: article.publishedAt }) ); } @@ -29,7 +29,7 @@ const makePublishArticle = await articleRepository.store(publishedArticle); logger.info( - getMessage("article.published", { id: publishedArticle.id.value, publishedAt: publishedArticle.publishedAt }) + getMessage('article.published', { id: publishedArticle.id.value, publishedAt: publishedArticle.publishedAt }) ); }; diff --git a/src/article/domain/Article.ts b/src/article/domain/Article.ts index 6c8963e..5bd83bb 100644 --- a/src/article/domain/Article.ts +++ b/src/article/domain/Article.ts @@ -1,20 +1,20 @@ -import { AggregateRoot } from "@/_lib/DDD"; -import { makeWithInvariants } from "@/_lib/WithInvariants"; -import { ArticleId } from "@/_sharedKernel/domain/ArticleId"; +import { AggregateRoot } from '@/_lib/DDD'; +import { makeWithInvariants } from '@/_lib/WithInvariants'; +import { ArticleId } from '@/_sharedKernel/domain/ArticleId'; namespace Article { type Article = AggregateRoot & Readonly<{ title: string; content: string; - state: "DRAFT" | "PUBLISHED" | "DELETED"; + state: 'DRAFT' | 'PUBLISHED' | 'DELETED'; publishedAt: Date | null; createdAt: Date; updatedAt: Date; version: number; }>; - type PublishedArticle = Omit & Readonly<{ state: "PUBLISHED"; publishedAt: Date }>; + type PublishedArticle = Omit & Readonly<{ state: 'PUBLISHED'; publishedAt: Date }>; const withInvariants = makeWithInvariants
((self, assert) => { assert(self.title?.length > 0); @@ -32,7 +32,7 @@ namespace Article { id: props.id, title: props.title, content: props.content, - state: "DRAFT", + state: 'DRAFT', publishedAt: null, createdAt: new Date(), updatedAt: new Date(), @@ -43,7 +43,7 @@ namespace Article { export const publish = withInvariants( (self: Article): PublishedArticle => ({ ...self, - state: "PUBLISHED", + state: 'PUBLISHED', publishedAt: new Date(), }) ); @@ -51,7 +51,7 @@ namespace Article { export const markAsDeleted = withInvariants( (self: Article): Article => ({ ...self, - state: "DELETED", + state: 'DELETED', }) ); @@ -62,7 +62,7 @@ namespace Article { }) ); - export const isPublished = (self: Article): self is PublishedArticle => self.state === "PUBLISHED"; + export const isPublished = (self: Article): self is PublishedArticle => self.state === 'PUBLISHED'; export type Type = Article; } diff --git a/src/article/domain/ArticleRepository.d.ts b/src/article/domain/ArticleRepository.d.ts index 9a5fcd9..ce07bb0 100644 --- a/src/article/domain/ArticleRepository.d.ts +++ b/src/article/domain/ArticleRepository.d.ts @@ -1,5 +1,5 @@ -import { Article } from "@/article/domain/Article"; -import { Repository } from "@/_lib/DDD"; +import { Article } from '@/article/domain/Article'; +import { Repository } from '@/_lib/DDD'; type ArticleRepository = Repository & { findById(id: string): Promise; diff --git a/src/article/index.ts b/src/article/index.ts index 14d2ecb..cfabeda 100644 --- a/src/article/index.ts +++ b/src/article/index.ts @@ -1,21 +1,21 @@ -import { asFunction } from "awilix"; -import { CreateArticle, makeCreateArticle } from "@/article/application/useCases/CreateArticle"; -import { DeleteArticle, makeDeleteArticle } from "@/article/application/useCases/DeleteArticle"; -import { makePublishArticle, PublishArticle } from "@/article/application/useCases/PublishArticle"; -import { ArticleRepository } from "@/article/domain/ArticleRepository"; -import { ArticleCollection, initArticleCollection } from "@/article/infrastructure/ArticleCollection"; -import { makeMongoArticleRepository } from "@/article/infrastructure/MongoArticleRepository"; -import { makeArticleController } from "@/article/interface/http/articleController"; -import { FindArticles } from "@/article/query/FindArticles"; -import { withMongoProvider } from "@/_lib/MongoProvider"; -import { toContainerValues } from "@/_lib/di/containerAdapters"; -import { makeMongoFindArticles } from "@/article/query/impl/MongoFindArticles"; -import { makeModule } from "@/context"; -import { makeArticleCreatedEmailListener } from "@/article/interface/email/ArticleCreatedEmailListener"; -import { articleMessages } from "@/article/messages"; +import { asFunction } from 'awilix'; +import { CreateArticle, makeCreateArticle } from '@/article/application/useCases/CreateArticle'; +import { DeleteArticle, makeDeleteArticle } from '@/article/application/useCases/DeleteArticle'; +import { makePublishArticle, PublishArticle } from '@/article/application/useCases/PublishArticle'; +import { ArticleRepository } from '@/article/domain/ArticleRepository'; +import { ArticleCollection, initArticleCollection } from '@/article/infrastructure/ArticleCollection'; +import { makeMongoArticleRepository } from '@/article/infrastructure/MongoArticleRepository'; +import { makeArticleController } from '@/article/interface/http/articleController'; +import { FindArticles } from '@/article/query/FindArticles'; +import { withMongoProvider } from '@/_lib/MongoProvider'; +import { toContainerValues } from '@/_lib/di/containerAdapters'; +import { makeMongoFindArticles } from '@/article/query/impl/MongoFindArticles'; +import { makeModule } from '@/context'; +import { makeArticleCreatedEmailListener } from '@/article/interface/email/ArticleCreatedEmailListener'; +import { articleMessages } from '@/article/messages'; const articleModule = makeModule( - "article", + 'article', async ({ container: { register, build }, messageBundle: { updateBundle } }) => { const collections = await build( withMongoProvider({ diff --git a/src/article/infrastructure/ArticleCollection.ts b/src/article/infrastructure/ArticleCollection.ts index f800250..758d781 100644 --- a/src/article/infrastructure/ArticleCollection.ts +++ b/src/article/infrastructure/ArticleCollection.ts @@ -1,11 +1,11 @@ -import { Collection, Db } from "mongodb"; -import { MUUID } from "uuid-mongodb"; +import { Collection, Db } from 'mongodb'; +import { MUUID } from 'uuid-mongodb'; type ArticleSchema = { _id: MUUID; title: string; content: string; - status: "DRAFT" | "PUBLISHED" | "DELETED"; + status: 'DRAFT' | 'PUBLISHED' | 'DELETED'; publishedAt: Date | null; deleted: boolean; createdAt: Date; @@ -16,7 +16,7 @@ type ArticleSchema = { type ArticleCollection = Collection; const initArticleCollection = async (db: Db): Promise => { - const collection: ArticleCollection = db.collection("article"); + const collection: ArticleCollection = db.collection('article'); await collection.createIndex({ title: 1 }, { unique: true }); await collection.createIndex({ _id: 1, version: 1 }); diff --git a/src/article/infrastructure/ArticleMapper.ts b/src/article/infrastructure/ArticleMapper.ts index 0b76b1e..2170446 100644 --- a/src/article/infrastructure/ArticleMapper.ts +++ b/src/article/infrastructure/ArticleMapper.ts @@ -1,8 +1,8 @@ -import { Article } from "@/article/domain/Article"; -import { ArticleSchema } from "@/article/infrastructure/ArticleCollection"; -import { DataMapper } from "@/_lib/DDD"; -import { ArticleIdProvider } from "@/_sharedKernel/infrastructure/ArticleIdProvider"; -import { from } from "uuid-mongodb"; +import { Article } from '@/article/domain/Article'; +import { ArticleSchema } from '@/article/infrastructure/ArticleCollection'; +import { DataMapper } from '@/_lib/DDD'; +import { ArticleIdProvider } from '@/_sharedKernel/infrastructure/ArticleIdProvider'; +import { from } from 'uuid-mongodb'; const ArticleMapper: DataMapper = { toData: (entity: Article.Type) => ({ @@ -12,7 +12,7 @@ const ArticleMapper: DataMapper = { status: entity.state, publishedAt: entity.publishedAt, createdAt: entity.createdAt, - deleted: entity.state === "DELETED", + deleted: entity.state === 'DELETED', updatedAt: entity.createdAt, version: entity.version, }), diff --git a/src/article/infrastructure/MongoArticleRepository.ts b/src/article/infrastructure/MongoArticleRepository.ts index 53a23c7..def27b4 100644 --- a/src/article/infrastructure/MongoArticleRepository.ts +++ b/src/article/infrastructure/MongoArticleRepository.ts @@ -1,10 +1,10 @@ -import { Article } from "@/article/domain/Article"; -import { ArticleRepository } from "@/article/domain/ArticleRepository"; -import { ArticleCollection } from "@/article/infrastructure/ArticleCollection"; -import { ArticleMapper } from "@/article/infrastructure/ArticleMapper"; -import { ArticleId } from "@/_sharedKernel/domain/ArticleId"; -import { ArticleIdProvider } from "@/_sharedKernel/infrastructure/ArticleIdProvider"; -import { from, v4 } from "uuid-mongodb"; +import { Article } from '@/article/domain/Article'; +import { ArticleRepository } from '@/article/domain/ArticleRepository'; +import { ArticleCollection } from '@/article/infrastructure/ArticleCollection'; +import { ArticleMapper } from '@/article/infrastructure/ArticleMapper'; +import { ArticleId } from '@/_sharedKernel/domain/ArticleId'; +import { ArticleIdProvider } from '@/_sharedKernel/infrastructure/ArticleIdProvider'; +import { from, v4 } from 'uuid-mongodb'; type Dependencies = { articleCollection: ArticleCollection; @@ -18,7 +18,7 @@ const makeMongoArticleRepository = ({ articleCollection }: Dependencies): Articl const article = await articleCollection.findOne({ _id: from(id), deleted: false }); if (!article) { - throw new Error("Article not found"); + throw new Error('Article not found'); } return ArticleMapper.toEntity(article); diff --git a/src/article/interface/email/ArticleCreatedEmailListener.ts b/src/article/interface/email/ArticleCreatedEmailListener.ts index 9049911..14a4986 100644 --- a/src/article/interface/email/ArticleCreatedEmailListener.ts +++ b/src/article/interface/email/ArticleCreatedEmailListener.ts @@ -1,7 +1,7 @@ -import { ArticleCreatedEvent } from "@/article/application/events/ArticleCreatedEvent"; -import { ArticleCollection } from "@/article/infrastructure/ArticleCollection"; -import { from } from "uuid-mongodb"; -import { eventConsumer } from "@/_lib/pubSub/EventEmitterConsumer"; +import { ArticleCreatedEvent } from '@/article/application/events/ArticleCreatedEvent'; +import { ArticleCollection } from '@/article/infrastructure/ArticleCollection'; +import { from } from 'uuid-mongodb'; +import { eventConsumer } from '@/_lib/pubSub/EventEmitterConsumer'; type Dependencies = { articleCollection: ArticleCollection; diff --git a/src/article/interface/http/articleController/CreateArticleHandler.ts b/src/article/interface/http/articleController/CreateArticleHandler.ts index 980f7c6..43fda2c 100644 --- a/src/article/interface/http/articleController/CreateArticleHandler.ts +++ b/src/article/interface/http/articleController/CreateArticleHandler.ts @@ -1,9 +1,9 @@ -import { CreateArticle } from "@/article/application/useCases/CreateArticle"; -import { makeValidator } from "@/_lib/http/validation/Validator"; -import { handler } from "@/_lib/http/handler"; -import { Request, Response } from "express"; -import Joi from "types-joi"; -import { HttpStatus } from "@/_lib/http/HttpStatus"; +import { CreateArticle } from '@/article/application/useCases/CreateArticle'; +import { makeValidator } from '@/_lib/http/validation/Validator'; +import { handler } from '@/_lib/http/handler'; +import { Request, Response } from 'express'; +import Joi from 'types-joi'; +import { HttpStatus } from '@/_lib/http/HttpStatus'; type Dependencies = { createArticle: CreateArticle; diff --git a/src/article/interface/http/articleController/DeleteArticleHandler.ts b/src/article/interface/http/articleController/DeleteArticleHandler.ts index c20d513..5f3ecc3 100644 --- a/src/article/interface/http/articleController/DeleteArticleHandler.ts +++ b/src/article/interface/http/articleController/DeleteArticleHandler.ts @@ -1,5 +1,5 @@ -import { DeleteArticle } from "@/article/application/useCases/DeleteArticle"; -import { handler } from "@/_lib/http/handler"; +import { DeleteArticle } from '@/article/application/useCases/DeleteArticle'; +import { handler } from '@/_lib/http/handler'; type Dependencies = { deleteArticle: DeleteArticle; diff --git a/src/article/interface/http/articleController/FindArticlesHandler.ts b/src/article/interface/http/articleController/FindArticlesHandler.ts index a5c2da3..f485187 100644 --- a/src/article/interface/http/articleController/FindArticlesHandler.ts +++ b/src/article/interface/http/articleController/FindArticlesHandler.ts @@ -1,7 +1,7 @@ -import { FindArticles } from "@/article/query/FindArticles"; -import { handler } from "@/_lib/http/handler"; -import Joi from "types-joi"; -import { makePaginator } from "@/_lib/http/validation/Paginator"; +import { FindArticles } from '@/article/query/FindArticles'; +import { handler } from '@/_lib/http/handler'; +import Joi from 'types-joi'; +import { makePaginator } from '@/_lib/http/validation/Paginator'; type Dependencies = { findArticles: FindArticles; diff --git a/src/article/interface/http/articleController/PublishArticleHandler.ts b/src/article/interface/http/articleController/PublishArticleHandler.ts index 9a6200c..2c6c558 100644 --- a/src/article/interface/http/articleController/PublishArticleHandler.ts +++ b/src/article/interface/http/articleController/PublishArticleHandler.ts @@ -1,6 +1,6 @@ -import { PublishArticle } from "@/article/application/useCases/PublishArticle"; -import { handler } from "@/_lib/http/handler"; -import { Request, Response } from "express"; +import { PublishArticle } from '@/article/application/useCases/PublishArticle'; +import { handler } from '@/_lib/http/handler'; +import { Request, Response } from 'express'; type Dependencies = { publishArticle: PublishArticle; diff --git a/src/article/interface/http/articleController/index.ts b/src/article/interface/http/articleController/index.ts index 78e0033..7f82756 100644 --- a/src/article/interface/http/articleController/index.ts +++ b/src/article/interface/http/articleController/index.ts @@ -1,8 +1,8 @@ -import { deleteArticleHandler } from "@/article/interface/http/articleController/DeleteArticleHandler"; -import { Router } from "express"; -import { createArticleHandler } from "./CreateArticleHandler"; -import { findArticlesHandler } from "./FindArticlesHandler"; -import { publishArticleHandler } from "./PublishArticleHandler"; +import { deleteArticleHandler } from '@/article/interface/http/articleController/DeleteArticleHandler'; +import { Router } from 'express'; +import { createArticleHandler } from './CreateArticleHandler'; +import { findArticlesHandler } from './FindArticlesHandler'; +import { publishArticleHandler } from './PublishArticleHandler'; type Dependencies = { apiRouter: Router; @@ -29,10 +29,10 @@ const makeArticleController = ({ apiRouter }: Dependencies) => { * items: * $ref: '#/definitions/ArticleDTO' */ - router.get("/articles", findArticlesHandler); - router.post("/articles", createArticleHandler); - router.delete("/articles/:articleId", deleteArticleHandler); - router.patch("/articles/:articleId/publish", publishArticleHandler); + router.get('/articles', findArticlesHandler); + router.post('/articles', createArticleHandler); + router.delete('/articles/:articleId', deleteArticleHandler); + router.patch('/articles/:articleId/publish', publishArticleHandler); apiRouter.use(router); }; diff --git a/src/article/messages.ts b/src/article/messages.ts index 1c887ae..5f0c841 100644 --- a/src/article/messages.ts +++ b/src/article/messages.ts @@ -1,4 +1,4 @@ -import { messageSource } from "@/_lib/message/MessageBundle"; +import { messageSource } from '@/_lib/message/MessageBundle'; type ArticleMessages = { article: { @@ -18,8 +18,8 @@ const articleMessages = messageSource({ "Can't republish the article #({{ id }}) because it was already published on {{ publishedAt.toISOString() }}", notFound: "Can't find article #({{ id }})", }, - created: "Article created with id #({{ id }})", - published: "Published article #({{ id }}) at {{ publishedAt.toISOString() }}", + created: 'Article created with id #({{ id }})', + published: 'Published article #({{ id }}) at {{ publishedAt.toISOString() }}', }, }); diff --git a/src/article/query/FindArticles.d.ts b/src/article/query/FindArticles.d.ts index 113b267..d4839bf 100644 --- a/src/article/query/FindArticles.d.ts +++ b/src/article/query/FindArticles.d.ts @@ -1,4 +1,4 @@ -import { PaginatedQuery, PaginatedQueryResult, QueryHandler, QueryResult, SortedPaginatedQuery } from "@/_lib/CQRS"; +import { PaginatedQuery, PaginatedQueryResult, QueryHandler, QueryResult, SortedPaginatedQuery } from '@/_lib/CQRS'; type ArticleListItemDTO = Readonly<{ id: string; diff --git a/src/article/query/impl/MongoFindArticles.ts b/src/article/query/impl/MongoFindArticles.ts index 112c4b0..a917fb0 100644 --- a/src/article/query/impl/MongoFindArticles.ts +++ b/src/article/query/impl/MongoFindArticles.ts @@ -1,8 +1,8 @@ -import { ArticleCollection, ArticleSchema } from "@/article/infrastructure/ArticleCollection"; -import MUUID from "uuid-mongodb"; -import { FindArticles } from "@/article/query/FindArticles"; -import { CommentSchema } from "@/comment/infrastructure/CommentCollection"; -import { Filter } from "mongodb"; +import { ArticleCollection, ArticleSchema } from '@/article/infrastructure/ArticleCollection'; +import MUUID from 'uuid-mongodb'; +import { FindArticles } from '@/article/query/FindArticles'; +import { CommentSchema } from '@/comment/infrastructure/CommentCollection'; +import { Filter } from 'mongodb'; type Dependencies = { articleCollection: ArticleCollection; @@ -12,14 +12,14 @@ const makeMongoFindArticles = ({ articleCollection }: Dependencies): FindArticles => async ({ pagination, filter, sort }) => { let match: Filter = { - status: "PUBLISHED", + status: 'PUBLISHED', deleted: false, }; if (filter.title) { match = { ...match, - title: { $regex: `^${filter.title}`, $options: "i" }, + title: { $regex: `^${filter.title}`, $options: 'i' }, }; } @@ -45,18 +45,18 @@ const makeMongoFindArticles = $limit: pagination.pageSize, }, ...(sort?.length - ? [{ $sort: sort.reduce((acc, { field, direction }) => ({ [field]: direction === "asc" ? 1 : -1 }), {}) }] + ? [{ $sort: sort.reduce((acc, { field, direction }) => ({ [field]: direction === 'asc' ? 1 : -1 }), {}) }] : []), { $lookup: { - from: "comment", - as: "comments", - let: { articleId: "$_id" }, + from: 'comment', + as: 'comments', + let: { articleId: '$_id' }, pipeline: [ { $match: { deleted: false, - $expr: { $eq: ["$articleId", "$$articleId"] }, + $expr: { $eq: ['$articleId', '$$articleId'] }, }, }, ], diff --git a/src/comment/application/useCases/CreateComment.ts b/src/comment/application/useCases/CreateComment.ts index 540e23f..67f282c 100644 --- a/src/comment/application/useCases/CreateComment.ts +++ b/src/comment/application/useCases/CreateComment.ts @@ -1,7 +1,7 @@ -import { ArticleRepository } from "@/article/domain/ArticleRepository"; -import { CommentRepository } from "@/comment/domain/CommentRepository"; -import { ApplicationService } from "@/_lib/DDD"; -import { Comment } from "@/comment/domain/Comment"; +import { ArticleRepository } from '@/article/domain/ArticleRepository'; +import { CommentRepository } from '@/comment/domain/CommentRepository'; +import { ApplicationService } from '@/_lib/DDD'; +import { Comment } from '@/comment/domain/Comment'; type Dependencies = { commentRepository: CommentRepository; diff --git a/src/comment/domain/Comment.ts b/src/comment/domain/Comment.ts index 06db147..c3c7b3d 100644 --- a/src/comment/domain/Comment.ts +++ b/src/comment/domain/Comment.ts @@ -1,9 +1,9 @@ -import { CommentId } from "@/comment/domain/CommentId"; -import { AggregateRoot } from "@/_lib/DDD"; -import { ArticleId } from "@/_sharedKernel/domain/ArticleId"; +import { CommentId } from '@/comment/domain/CommentId'; +import { AggregateRoot } from '@/_lib/DDD'; +import { ArticleId } from '@/_sharedKernel/domain/ArticleId'; namespace Comment { - type Status = "ACTIVE" | "DELETED"; + type Status = 'ACTIVE' | 'DELETED'; type Comment = AggregateRoot & Readonly<{ @@ -23,7 +23,7 @@ namespace Comment { export const create = (props: CommentProps): Comment => ({ ...props, - status: "ACTIVE", + status: 'ACTIVE', createdAt: new Date(), updatedAt: new Date(), version: 0, @@ -31,7 +31,7 @@ namespace Comment { export const markAsDeleted = (self: Comment): Comment => ({ ...self, - status: "DELETED", + status: 'DELETED', }); export type Type = Comment; diff --git a/src/comment/domain/CommentId.d.ts b/src/comment/domain/CommentId.d.ts index d056f10..67cc251 100644 --- a/src/comment/domain/CommentId.d.ts +++ b/src/comment/domain/CommentId.d.ts @@ -1,4 +1,4 @@ -import { AggregateId } from "@/_lib/DDD"; +import { AggregateId } from '@/_lib/DDD'; type CommentId = AggregateId; diff --git a/src/comment/domain/CommentRepository.d.ts b/src/comment/domain/CommentRepository.d.ts index 5f6633a..19a7594 100644 --- a/src/comment/domain/CommentRepository.d.ts +++ b/src/comment/domain/CommentRepository.d.ts @@ -1,9 +1,9 @@ -import { Comment } from "@/comment/domain/Comment"; -import { CommentId } from "@/comment/domain/CommentId"; -import { Repository } from "@/_lib/DDD"; +import { Comment } from '@/comment/domain/Comment'; +import { CommentId } from '@/comment/domain/CommentId'; +import { Repository } from '@/_lib/DDD'; type CommentRepository = Repository & { - findById(id: CommentId["value"]): Promise; + findById(id: CommentId['value']): Promise; }; export { CommentRepository }; diff --git a/src/comment/index.ts b/src/comment/index.ts index dde8635..549f790 100644 --- a/src/comment/index.ts +++ b/src/comment/index.ts @@ -1,14 +1,14 @@ -import { CreateComment, makeCreateComment } from "@/comment/application/useCases/CreateComment"; -import { CommentRepository } from "@/comment/domain/CommentRepository"; -import { CommentCollection, initCommentCollection } from "@/comment/infrastructure/CommentCollection"; -import { makeMongoCommentRepository } from "@/comment/infrastructure/MongoCommentRepository"; -import { makeCommentController } from "@/comment/interface/http/commentController"; -import { makeModule } from "@/context"; -import { withMongoProvider } from "@/_lib/MongoProvider"; -import { toContainerValues } from "@/_lib/di/containerAdapters"; -import { asFunction } from "awilix"; +import { CreateComment, makeCreateComment } from '@/comment/application/useCases/CreateComment'; +import { CommentRepository } from '@/comment/domain/CommentRepository'; +import { CommentCollection, initCommentCollection } from '@/comment/infrastructure/CommentCollection'; +import { makeMongoCommentRepository } from '@/comment/infrastructure/MongoCommentRepository'; +import { makeCommentController } from '@/comment/interface/http/commentController'; +import { makeModule } from '@/context'; +import { withMongoProvider } from '@/_lib/MongoProvider'; +import { toContainerValues } from '@/_lib/di/containerAdapters'; +import { asFunction } from 'awilix'; -const commentModule = makeModule("comment", async ({ container: { register, build } }) => { +const commentModule = makeModule('comment', async ({ container: { register, build } }) => { const collections = await build( withMongoProvider({ commentCollection: initCommentCollection, diff --git a/src/comment/infrastructure/CommentCollection.ts b/src/comment/infrastructure/CommentCollection.ts index 96cba6a..97f2259 100644 --- a/src/comment/infrastructure/CommentCollection.ts +++ b/src/comment/infrastructure/CommentCollection.ts @@ -1,11 +1,11 @@ -import { Collection, Db } from "mongodb"; -import { MUUID } from "uuid-mongodb"; +import { Collection, Db } from 'mongodb'; +import { MUUID } from 'uuid-mongodb'; type CommentSchema = { _id: MUUID; body: string; articleId: MUUID; - status: "ACTIVE" | "DELETED"; + status: 'ACTIVE' | 'DELETED'; deleted: boolean; createdAt: Date; updatedAt: Date; @@ -15,7 +15,7 @@ type CommentSchema = { type CommentCollection = Collection; const initCommentCollection = async (db: Db): Promise => { - const collection: CommentCollection = db.collection("comment"); + const collection: CommentCollection = db.collection('comment'); await collection.createIndex({ _id: 1, version: 1 }); await collection.createIndex({ _id: 1, deleted: 1 }); diff --git a/src/comment/infrastructure/CommentIdProvider.ts b/src/comment/infrastructure/CommentIdProvider.ts index 7559291..834387b 100644 --- a/src/comment/infrastructure/CommentIdProvider.ts +++ b/src/comment/infrastructure/CommentIdProvider.ts @@ -1,6 +1,6 @@ -import { CommentId } from "@/comment/domain/CommentId"; -import { makeIdProvider } from "@/_lib/IdProvider"; +import { CommentId } from '@/comment/domain/CommentId'; +import { makeIdProvider } from '@/_lib/IdProvider'; -const CommentIdProvider = makeIdProvider("CommentId"); +const CommentIdProvider = makeIdProvider('CommentId'); export { CommentIdProvider }; diff --git a/src/comment/infrastructure/CommentMapper.ts b/src/comment/infrastructure/CommentMapper.ts index d5cbd2d..18e1892 100644 --- a/src/comment/infrastructure/CommentMapper.ts +++ b/src/comment/infrastructure/CommentMapper.ts @@ -1,9 +1,9 @@ -import { Comment } from "@/comment/domain/Comment"; -import { CommentSchema } from "@/comment/infrastructure/CommentCollection"; -import { CommentIdProvider } from "@/comment/infrastructure/CommentIdProvider"; -import { DataMapper } from "@/_lib/DDD"; -import { ArticleIdProvider } from "@/_sharedKernel/infrastructure/ArticleIdProvider"; -import { from } from "uuid-mongodb"; +import { Comment } from '@/comment/domain/Comment'; +import { CommentSchema } from '@/comment/infrastructure/CommentCollection'; +import { CommentIdProvider } from '@/comment/infrastructure/CommentIdProvider'; +import { DataMapper } from '@/_lib/DDD'; +import { ArticleIdProvider } from '@/_sharedKernel/infrastructure/ArticleIdProvider'; +import { from } from 'uuid-mongodb'; const CommentMapper: DataMapper = { toData: (entity) => ({ @@ -11,7 +11,7 @@ const CommentMapper: DataMapper = { body: entity.body, articleId: from(entity.articleId.value), status: entity.status, - deleted: entity.status === "DELETED", + deleted: entity.status === 'DELETED', createdAt: entity.createdAt, updatedAt: entity.updatedAt, version: entity.version, diff --git a/src/comment/infrastructure/MongoCommentRepository.ts b/src/comment/infrastructure/MongoCommentRepository.ts index 485f0b7..608b19d 100644 --- a/src/comment/infrastructure/MongoCommentRepository.ts +++ b/src/comment/infrastructure/MongoCommentRepository.ts @@ -1,11 +1,11 @@ -import { Comment } from "@/comment/domain/Comment"; -import { CommentId } from "@/comment/domain/CommentId"; -import { CommentRepository } from "@/comment/domain/CommentRepository"; -import { CommentCollection } from "@/comment/infrastructure/CommentCollection"; -import { CommentIdProvider } from "@/comment/infrastructure/CommentIdProvider"; -import { CommentMapper } from "@/comment/infrastructure/CommentMapper"; -import { ArticleIdProvider } from "@/_sharedKernel/infrastructure/ArticleIdProvider"; -import { from, v4 } from "uuid-mongodb"; +import { Comment } from '@/comment/domain/Comment'; +import { CommentId } from '@/comment/domain/CommentId'; +import { CommentRepository } from '@/comment/domain/CommentRepository'; +import { CommentCollection } from '@/comment/infrastructure/CommentCollection'; +import { CommentIdProvider } from '@/comment/infrastructure/CommentIdProvider'; +import { CommentMapper } from '@/comment/infrastructure/CommentMapper'; +import { ArticleIdProvider } from '@/_sharedKernel/infrastructure/ArticleIdProvider'; +import { from, v4 } from 'uuid-mongodb'; type Dependencies = { commentCollection: CommentCollection; @@ -19,7 +19,7 @@ const makeMongoCommentRepository = ({ commentCollection }: Dependencies): Commen const comment = await commentCollection.findOne({ _id: from(id), deleted: false }); if (!comment) { - throw new Error("Comment not found"); + throw new Error('Comment not found'); } return CommentMapper.toEntity(comment); diff --git a/src/comment/interface/http/commentController/CreateCommentHandler.ts b/src/comment/interface/http/commentController/CreateCommentHandler.ts index 808ba09..be565f4 100644 --- a/src/comment/interface/http/commentController/CreateCommentHandler.ts +++ b/src/comment/interface/http/commentController/CreateCommentHandler.ts @@ -1,7 +1,7 @@ -import { CreateComment } from "@/comment/application/useCases/CreateComment"; -import { makeValidator } from "@/_lib/http/validation/Validator"; -import { handler } from "@/_lib/http/handler"; -import Joi from "types-joi"; +import { CreateComment } from '@/comment/application/useCases/CreateComment'; +import { makeValidator } from '@/_lib/http/validation/Validator'; +import { handler } from '@/_lib/http/handler'; +import Joi from 'types-joi'; type Dependencies = { createComment: CreateComment; diff --git a/src/comment/interface/http/commentController/index.ts b/src/comment/interface/http/commentController/index.ts index f675d93..a1ffd32 100644 --- a/src/comment/interface/http/commentController/index.ts +++ b/src/comment/interface/http/commentController/index.ts @@ -1,5 +1,5 @@ -import { createCommentHandler } from "@/comment/interface/http/commentController/CreateCommentHandler"; -import { Router } from "express"; +import { createCommentHandler } from '@/comment/interface/http/commentController/CreateCommentHandler'; +import { Router } from 'express'; type Dependencies = { apiRouter: Router; @@ -8,7 +8,7 @@ type Dependencies = { const makeCommentController = ({ apiRouter }: Dependencies) => { const router = Router(); - router.post("/articles/:articleId/comments", createCommentHandler); + router.post('/articles/:articleId/comments', createCommentHandler); apiRouter.use(router); }; diff --git a/src/config.ts b/src/config.ts index b6c6574..bf2e12c 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,34 +1,34 @@ -import { REPLConfig } from "@/_boot/repl"; -import { environment, EnvironmentConfig, envNumber, envString } from "@/_lib/Environment"; -import { ServerConfig } from "@/_boot/server"; -import { DatabaseConfig } from "@/_boot/database"; -import { SwaggerConfig } from "@/_boot/swagger"; -import { AppModulesConfig } from "@/_boot/appModules"; +import { REPLConfig } from '@/_boot/repl'; +import { environment, EnvironmentConfig, envNumber, envString } from '@/_lib/Environment'; +import { ServerConfig } from '@/_boot/server'; +import { DatabaseConfig } from '@/_boot/database'; +import { SwaggerConfig } from '@/_boot/swagger'; +import { AppModulesConfig } from '@/_boot/appModules'; type Configuration = ServerConfig & DatabaseConfig & EnvironmentConfig & REPLConfig & SwaggerConfig & AppModulesConfig; const config: Configuration = { - appName: "node-api-boilerplate", - cli: process.argv.includes("--cli"), + appName: 'node-api-boilerplate', + cli: process.argv.includes('--cli'), environment: environment(), repl: { - port: envNumber("REPL_PORT", 2580), + port: envNumber('REPL_PORT', 2580), }, http: { - host: envString("HOST", "localhost"), - port: envNumber("PORT", 3000), + host: envString('HOST', 'localhost'), + port: envNumber('PORT', 3000), }, swagger: { - title: "Blog API", - version: "1.0.0", - basePath: "/api", - docEndpoint: "/api-docs", + title: 'Blog API', + version: '1.0.0', + basePath: '/api', + docEndpoint: '/api-docs', }, mongodb: { - database: envString("DB_NAME", "blog"), - host: envString("DB_HOST", "mongodb://localhost:27017"), - username: envString("DB_USER", "blog"), - password: envString("DB_PASS", "blog"), + database: envString('DB_NAME', 'blog'), + host: envString('DB_HOST', 'mongodb://localhost:27017'), + username: envString('DB_USER', 'blog'), + password: envString('DB_PASS', 'blog'), }, }; diff --git a/src/container.ts b/src/container.ts index eb482d4..022905e 100644 --- a/src/container.ts +++ b/src/container.ts @@ -1,9 +1,9 @@ -import { createContainer } from "awilix"; -import { MainRegistry } from "@/_boot"; -import { DatabaseRegistry } from "@/_boot/database"; -import { ServerRegistry } from "@/_boot/server"; -import { PubSubRegistry } from "@/_boot/pubSub"; -import { AppModulesRegistry } from "@/_boot/appModules"; +import { createContainer } from 'awilix'; +import { MainRegistry } from '@/_boot'; +import { DatabaseRegistry } from '@/_boot/database'; +import { ServerRegistry } from '@/_boot/server'; +import { PubSubRegistry } from '@/_boot/pubSub'; +import { AppModulesRegistry } from '@/_boot/appModules'; type Registry = MainRegistry & DatabaseRegistry & ServerRegistry & PubSubRegistry & AppModulesRegistry; diff --git a/src/context.ts b/src/context.ts index 4d96108..a4fe9ff 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1,8 +1,8 @@ -import { makeContext } from "@/_lib/Context"; -import { container } from "@/container"; -import { config } from "@/config"; -import { logger } from "@/_lib/logger"; -import { messageBundle } from "@/messages"; +import { makeContext } from '@/_lib/Context'; +import { container } from '@/container'; +import { config } from '@/config'; +import { logger } from '@/_lib/logger'; +import { messageBundle } from '@/messages'; const { withContext, makeModule } = makeContext({ config, container, logger, messageBundle }, { logger }); diff --git a/src/index.ts b/src/index.ts index bd8f65c..3a5aebb 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,17 +1,17 @@ -import("tsconfig-paths") +import('tsconfig-paths') .then(({ register }) => { register({ baseUrl: __dirname, - paths: { "@/*": ["*"] }, + paths: { '@/*': ['*'] }, addMatchAll: false, }); }) - .then(() => import("@/_boot")) + .then(() => import('@/_boot')) .then(({ main }) => main()) .catch((err) => { console.error(err); - if (process.env.NODE_ENV === "production") { - process.kill(process.pid, "SIGTERM"); + if (process.env.NODE_ENV === 'production') { + process.kill(process.pid, 'SIGTERM'); } }); diff --git a/src/messages.ts b/src/messages.ts index 6bc594b..a332b28 100644 --- a/src/messages.ts +++ b/src/messages.ts @@ -1,5 +1,5 @@ -import { AppModulesMessages } from "@/_boot/appModules"; -import { makeMessegeBundle } from "@/_lib/message/MessageBundle"; +import { AppModulesMessages } from '@/_boot/appModules'; +import { makeMessegeBundle } from '@/_lib/message/MessageBundle'; type Messages = AppModulesMessages;