diff --git a/example/express/yarn.lock b/example/express/yarn.lock index 074d576..35ceb88 100644 --- a/example/express/yarn.lock +++ b/example/express/yarn.lock @@ -1333,9 +1333,9 @@ ee-first@1.1.1: integrity sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0= electron-to-chromium@^1.4.84: - version "1.4.110" - resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.110.tgz#269208d7cf7e32123b1d87bf4e6e1fd9ac7ff51d" - integrity sha512-TvHZrkj9anfWkxgblHlNr4IMQdm2N6D0o8Wu1BDpSL/RKT4DHyUt/tvDFtApgZ+LGFL3U9EO4LRZ1eSlQ8xMYA== + version "1.4.111" + resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.111.tgz#897613f6504f3f17c9381c7499a635b413e4df4e" + integrity sha512-/s3+fwhKf1YK4k7btOImOzCQLpUjS6MaPf0ODTNuT4eTM1Bg4itBpLkydhOzJmpmH6Z9eXFyuuK5czsmzRzwtw== emoji-regex@^8.0.0: version "8.0.0" diff --git a/example/fastify/yarn.lock b/example/fastify/yarn.lock index 48bc94a..37c14e9 100644 --- a/example/fastify/yarn.lock +++ b/example/fastify/yarn.lock @@ -1274,9 +1274,9 @@ ee-first@1.1.1: integrity sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0= electron-to-chromium@^1.4.84: - version "1.4.110" - resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.110.tgz#269208d7cf7e32123b1d87bf4e6e1fd9ac7ff51d" - integrity sha512-TvHZrkj9anfWkxgblHlNr4IMQdm2N6D0o8Wu1BDpSL/RKT4DHyUt/tvDFtApgZ+LGFL3U9EO4LRZ1eSlQ8xMYA== + version "1.4.111" + resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.111.tgz#897613f6504f3f17c9381c7499a635b413e4df4e" + integrity sha512-/s3+fwhKf1YK4k7btOImOzCQLpUjS6MaPf0ODTNuT4eTM1Bg4itBpLkydhOzJmpmH6Z9eXFyuuK5czsmzRzwtw== emoji-regex@^8.0.0: version "8.0.0" diff --git a/lib/src/functions/api/index.js b/lib/src/functions/api/index.js index 93781c4..a52435c 100644 --- a/lib/src/functions/api/index.js +++ b/lib/src/functions/api/index.js @@ -4,6 +4,7 @@ const exec = util.promisify(require('child_process').exec) const writeFile = require('../../utils/writeFile') const database = require('./database') const schemas = require('./schemas') +const services = require('./services') /* * Express api: @@ -146,193 +147,6 @@ export * from './server' file: `${projectName}/src/network/index.ts` } }, - services: { - index: { - content: "export * from './user'\n", - file: `${projectName}/src/services/index.ts` - }, - user: { - content: `import httpErrors from 'http-errors' - -import { store, remove, get, update } from 'database' -import { UserDTO } from 'schemas' -import { EFU, MFU, GE, errorHandling } from './utils' - -type Process = { - type: 'store' | 'getAll' | 'deleteAll' | 'getOne' | 'update' | 'delete' -} - -type Arguments = { - id?: string - userDto?: UserDTO - userDtoWithoutId?: Omit -} - -class UserService { - #args: Arguments - - constructor(args: Arguments = {}) { - this.#args = args - } - - public process({ type }: Process): Promise { - switch (type) { - case 'store': - return this.#store() - case 'getAll': - return this.#getAll() - case 'deleteAll': - return this.#deleteAll() - case 'getOne': - return this.#getOne() - case 'update': - return this.#update() - case 'delete': - return this.#delete() - default: - throw new httpErrors.InternalServerError(GE.INTERNAL_SERVER_ERROR) - } - } - - async #store(): Promise { - try { - if (!this.#args.userDtoWithoutId) - throw new httpErrors.UnprocessableEntity(GE.INTERNAL_SERVER_ERROR) - - const result = await store({ - ...this.#args.userDtoWithoutId - }) - - return result - } catch (e) { - return errorHandling(e, GE.INTERNAL_SERVER_ERROR) - } - } - - async #getAll(): Promise { - try { - const users = (await get()) as UserDTO[] - - return users - } catch (e) { - return errorHandling(e, GE.INTERNAL_SERVER_ERROR) - } - } - - async #deleteAll(): Promise { - try { - const usersDeleted = (await remove()) as number - - if (usersDeleted >= 1) return MFU.ALL_USERS_DELETED - - if (usersDeleted === 0) - throw new httpErrors.Conflict(EFU.NOTHING_TO_DELETE) - - throw new httpErrors.InternalServerError(GE.INTERNAL_SERVER_ERROR) - } catch (e) { - return errorHandling(e, GE.INTERNAL_SERVER_ERROR) - } - } - - async #getOne(): Promise { - try { - if (!this.#args.id) - throw new httpErrors.UnprocessableEntity(GE.INTERNAL_SERVER_ERROR) - - const { id } = this.#args - const user = (await get(id)) as UserDTO | null - - if (!user) throw new httpErrors.NotFound(EFU.NOT_FOUND) - - return user - } catch (e) { - return errorHandling(e, GE.INTERNAL_SERVER_ERROR) - } - } - - async #update(): Promise { - try { - if (!this.#args.userDto || !this.#args.userDto.id) - throw new httpErrors.UnprocessableEntity(GE.INTERNAL_SERVER_ERROR) - - const updatedUser = await update(this.#args.userDto) - - if (!updatedUser) throw new httpErrors.NotFound(EFU.NOT_FOUND) - - return updatedUser - } catch (e) { - return errorHandling(e, GE.INTERNAL_SERVER_ERROR) - } - } - - async #delete(): Promise { - try { - if (!this.#args.id) - throw new httpErrors.UnprocessableEntity(GE.INTERNAL_SERVER_ERROR) - - const { id } = this.#args - const deletedUser = await remove(id) - - if (!deletedUser) throw new httpErrors.NotFound(EFU.NOT_FOUND) - - return MFU.USER_DELETED - } catch (e) { - return errorHandling(e, GE.INTERNAL_SERVER_ERROR) - } - } -} - -export { UserService } -`, - file: `${projectName}/src/services/user.ts` - } - }, - 'services/utils': { - index: { - content: `import httpErrors from 'http-errors' - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const errorHandling = (e: any, message?: string): never => { - console.error(e) - - if (e instanceof httpErrors.HttpError) throw e - - throw new httpErrors.InternalServerError(message ?? e.message) -} - -export { errorHandling } -export * from './messages' -`, - file: `${projectName}/src/services/utils/index.ts` - } - }, - 'services/utils/messages': { - index: { - content: `enum GenericErrors { - INTERNAL_SERVER_ERROR = 'Something went wrong' -} - -export { GenericErrors as GE } -export * from './user' -`, - file: `${projectName}/src/services/utils/messages/index.ts` - }, - user: { - content: `enum ErrorForUser { - NOT_FOUND = 'The requested user does not exists', - NOTHING_TO_DELETE = 'There is no user to be deleted' -} - -enum MessageForUser { - ALL_USERS_DELETED = 'All the users were deleted successfully', - USER_DELETED = 'The requested user was successfully deleted' -} - -export { ErrorForUser as EFU, MessageForUser as MFU } -`, - file: `${projectName}/src/services/utils/messages/user.ts` - } - }, test: { index: { content: `### Testing store a user @@ -1687,9 +1501,6 @@ ${projectName}/src/@types \ ${projectName}/src/@types/models \ ${projectName}/src/network \ ${projectName}/src/network/routes \ -${projectName}/src/services \ -${projectName}/src/services/utils \ -${projectName}/src/services/utils/messages \ ${fastify ? `${fastifyFolders}` : `${expressFolders}`} ` @@ -1704,6 +1515,8 @@ ${fastify ? `${fastifyFolders}` : `${expressFolders}`} }) // /schemas schemas({ projectName }) + // /services + services({ projectName }) // /@types await writeFile(data['@types'].index.file, data['@types'].index.content) @@ -1714,26 +1527,6 @@ ${fastify ? `${fastifyFolders}` : `${expressFolders}`} data['@types/models'].user.content ) - // /services - await writeFile(data.services.user.file, data.services.user.content) - await writeFile(data.services.index.file, data.services.index.content) - - // /services/utils - await writeFile( - data['services/utils'].index.file, - data['services/utils'].index.content - ) - - // /services/utils/messages - await writeFile( - data['services/utils/messages'].user.file, - data['services/utils/messages'].user.content - ) - await writeFile( - data['services/utils/messages'].index.file, - data['services/utils/messages'].index.content - ) - // /network await writeFile(data.network.index.file, data.network.index.content) diff --git a/lib/src/functions/api/services.js b/lib/src/functions/api/services.js new file mode 100644 index 0000000..2c31108 --- /dev/null +++ b/lib/src/functions/api/services.js @@ -0,0 +1,214 @@ +const { platform } = require('os') +const { promisify } = require('util') +const exec = promisify(require('child_process').exec) +const writeFile = require('../../utils/writeFile') + +module.exports = async ({ projectName }) => { + const createFoldersCommand = `mkdir ${projectName}/src/services \ +${projectName}/src/services/utils \ +${projectName}/src/services/utils/messages` + + if (platform() === 'win32') + await exec(createFoldersCommand.replaceAll('/', '\\')) + else await exec(createFoldersCommand) + + const services = { + index: { + content: "export * from './user'\n", + file: `${projectName}/src/services/index.ts` + }, + user: { + content: `import httpErrors from 'http-errors' + +import { store, remove, get, update } from 'database' +import { UserDTO } from 'schemas' +import { EFU, MFU, GE, errorHandling } from './utils' + +type Process = { + type: 'store' | 'getAll' | 'deleteAll' | 'getOne' | 'update' | 'delete' +} + +type Arguments = { + id?: string + userDto?: UserDTO + userDtoWithoutId?: Omit +} + +class UserService { + #args: Arguments + + constructor(args: Arguments = {}) { + this.#args = args + } + + public process({ type }: Process): Promise { + switch (type) { + case 'store': + return this.#store() + case 'getAll': + return this.#getAll() + case 'deleteAll': + return this.#deleteAll() + case 'getOne': + return this.#getOne() + case 'update': + return this.#update() + case 'delete': + return this.#delete() + default: + throw new httpErrors.InternalServerError(GE.INTERNAL_SERVER_ERROR) + } + } + + async #store(): Promise { + try { + if (!this.#args.userDtoWithoutId) + throw new httpErrors.UnprocessableEntity(GE.INTERNAL_SERVER_ERROR) + + const result = await store({ + ...this.#args.userDtoWithoutId + }) + + return result + } catch (e) { + return errorHandling(e, GE.INTERNAL_SERVER_ERROR) + } + } + + async #getAll(): Promise { + try { + const users = (await get()) as UserDTO[] + + return users + } catch (e) { + return errorHandling(e, GE.INTERNAL_SERVER_ERROR) + } + } + + async #deleteAll(): Promise { + try { + const usersDeleted = (await remove()) as number + + if (usersDeleted >= 1) return MFU.ALL_USERS_DELETED + + if (usersDeleted === 0) + throw new httpErrors.Conflict(EFU.NOTHING_TO_DELETE) + + throw new httpErrors.InternalServerError(GE.INTERNAL_SERVER_ERROR) + } catch (e) { + return errorHandling(e, GE.INTERNAL_SERVER_ERROR) + } + } + + async #getOne(): Promise { + try { + if (!this.#args.id) + throw new httpErrors.UnprocessableEntity(GE.INTERNAL_SERVER_ERROR) + + const { id } = this.#args + const user = (await get(id)) as UserDTO | null + + if (!user) throw new httpErrors.NotFound(EFU.NOT_FOUND) + + return user + } catch (e) { + return errorHandling(e, GE.INTERNAL_SERVER_ERROR) + } + } + + async #update(): Promise { + try { + if (!this.#args.userDto || !this.#args.userDto.id) + throw new httpErrors.UnprocessableEntity(GE.INTERNAL_SERVER_ERROR) + + const updatedUser = await update(this.#args.userDto) + + if (!updatedUser) throw new httpErrors.NotFound(EFU.NOT_FOUND) + + return updatedUser + } catch (e) { + return errorHandling(e, GE.INTERNAL_SERVER_ERROR) + } + } + + async #delete(): Promise { + try { + if (!this.#args.id) + throw new httpErrors.UnprocessableEntity(GE.INTERNAL_SERVER_ERROR) + + const { id } = this.#args + const deletedUser = await remove(id) + + if (!deletedUser) throw new httpErrors.NotFound(EFU.NOT_FOUND) + + return MFU.USER_DELETED + } catch (e) { + return errorHandling(e, GE.INTERNAL_SERVER_ERROR) + } + } +} + +export { UserService } +`, + file: `${projectName}/src/services/user.ts` + }, + utils: { + index: { + content: `import httpErrors from 'http-errors' + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const errorHandling = (e: any, message?: string): never => { + console.error(e) + + if (e instanceof httpErrors.HttpError) throw e + + throw new httpErrors.InternalServerError(message ?? e.message) +} + +export { errorHandling } +export * from './messages' +`, + file: `${projectName}/src/services/utils/index.ts` + } + }, + 'utils/messages': { + index: { + content: `enum GenericErrors { + INTERNAL_SERVER_ERROR = 'Something went wrong' +} + +export { GenericErrors as GE } +export * from './user' +`, + file: `${projectName}/src/services/utils/messages/index.ts` + }, + user: { + content: `enum ErrorForUser { + NOT_FOUND = 'The requested user does not exists', + NOTHING_TO_DELETE = 'There is no user to be deleted' +} + +enum MessageForUser { + ALL_USERS_DELETED = 'All the users were deleted successfully', + USER_DELETED = 'The requested user was successfully deleted' +} + +export { ErrorForUser as EFU, MessageForUser as MFU } +`, + file: `${projectName}/src/services/utils/messages/user.ts` + } + } + } + + await writeFile(services.index.file, services.index.content) + await writeFile(services.user.file, services.user.content) + await writeFile(services.utils.index.file, services.utils.index.content) + await writeFile( + services['utils/messages'].index.file, + services['utils/messages'].index.content + ) + await writeFile( + services['utils/messages'].user.file, + services['utils/messages'].user.content + ) +} diff --git a/lib/src/utils/writeFile.js b/lib/src/utils/writeFile.js index 52a533a..ce44b23 100644 --- a/lib/src/utils/writeFile.js +++ b/lib/src/utils/writeFile.js @@ -1,4 +1,4 @@ -const fs = require('fs') +const { writeFile } = require('fs') /** * @param {String} filename @@ -7,7 +7,7 @@ const fs = require('fs') */ module.exports = (filename, data) => { return new Promise((resolve, reject) => { - fs.writeFile(filename, data, error => { + writeFile(filename, data, error => { if (error) reject(error.message) else resolve('Saved successfully') })