From dc44ca7c8191115f8ce7e15630cb4821759b1e30 Mon Sep 17 00:00:00 2001 From: guimroque Date: Wed, 12 Jun 2024 15:56:14 -0300 Subject: [PATCH 01/11] fix: increase typeorm version --- packages/api/package.json | 4 +- packages/api/src/config/database.ts | 22 +- .../1714734332092-update-predicate-version.ts | 4 +- .../seeders/110820231840-create-users.ts | 10 +- packages/api/src/middlewares/auth/index.ts | 2 +- .../mocks/initialSeeds/initialPredicate.ts | 4 +- packages/api/src/modules/auth/controller.ts | 2 +- packages/api/src/modules/dApps/service.ts | 8 +- .../api/src/modules/notification/services.ts | 22 +- .../api/src/modules/predicate/services.ts | 342 +++++++++--------- .../src/modules/predicateVersion/services.ts | 6 +- .../api/src/modules/recoverCode/services.ts | 81 +++-- .../api/src/modules/transaction/controller.ts | 1 - .../api/src/modules/transaction/services.ts | 11 +- packages/api/src/modules/user/controller.ts | 2 +- .../api/src/modules/vaultTemplate/services.ts | 10 +- .../api/src/modules/workspace/controller.ts | 2 +- .../api/src/modules/workspace/services.ts | 46 ++- packages/api/src/utils/error/Unauthorized.ts | 9 - packages/api/src/utils/error/index.ts | 3 + packages/api/src/utils/token/utils.ts | 4 +- 21 files changed, 324 insertions(+), 271 deletions(-) diff --git a/packages/api/package.json b/packages/api/package.json index f7a8de3b3..ab3210646 100644 --- a/packages/api/package.json +++ b/packages/api/package.json @@ -5,7 +5,7 @@ "license": "Apache-2.0", "scripts": { "dev": "NODE_ENV=development ts-node-dev --respawn --transpile-only -r tsconfig-paths/register -r dotenv/config src/server/index.ts", - "test": "NODE_ENV=test node --experimental-vm-modules ./node_modules/jest/bin/jest.js --setupFiles dotenv/config --runInBand", + "test": "NODE_ENV=test node --experimental-vm-modules ./node_modules/jest/bin/jest.js --setupFiles dotenv/config --runInBand ", "start": "pm2-runtime start ./build/server/index.js", "build": "tsc --project . && tscpaths -p tsconfig.json -s ./src -o ./build", "copyFiles": "copyfiles --error --up 1 src/**/*.html build", @@ -50,7 +50,7 @@ "socket.io-client": "4.7.5", "ts-node": "^10.9.2", "tsconfig-paths": "^3.15.0", - "typeorm": "^0.2.45", + "typeorm": "0.3.20", "typescript": "^4.9.5" }, "devDependencies": { diff --git a/packages/api/src/config/database.ts b/packages/api/src/config/database.ts index 2df734cae..e4187cc28 100644 --- a/packages/api/src/config/database.ts +++ b/packages/api/src/config/database.ts @@ -42,10 +42,6 @@ const development: ConnectionOptions = { database: DATABASE_NAME, entities: [entitiesDir], migrations: [migrationsDir, seedersDir], - cli: { - entitiesDir: './src/models/', - migrationsDir: './src/database/migrations/', - }, synchronize: false, migrationsRun: true, }; @@ -59,10 +55,6 @@ const test: ConnectionOptions = { database: DATABASE_NAME, entities: [entitiesDir], migrations: [migrationsDir, seedersDir], - cli: { - entitiesDir: './src/models/', - migrationsDir: './src/database/migrations/', - }, synchronize: false, migrationsRun: true, }; @@ -76,11 +68,10 @@ const production: ConnectionOptions = { database: process.env.DATABASE_NAME, entities: [entitiesDir], migrations: [migrationsDir, seedersDir], - cli: { - entitiesDir: './src/models/', - migrationsDir: './src/database/migrations/', - }, synchronize: false, + ssl: { + rejectUnauthorized: false, + }, migrationsRun: true, }; @@ -93,11 +84,10 @@ const staging: ConnectionOptions = { database: process.env.DATABASE_NAME, entities: [entitiesDir], migrations: [migrationsDir, seedersDir], - cli: { - entitiesDir: './src/models/', - migrationsDir: './src/database/migrations/', - }, synchronize: false, + ssl: { + rejectUnauthorized: false, + }, migrationsRun: true, }; diff --git a/packages/api/src/database/migrations/1714734332092-update-predicate-version.ts b/packages/api/src/database/migrations/1714734332092-update-predicate-version.ts index e6e28a11f..f56955f01 100644 --- a/packages/api/src/database/migrations/1714734332092-update-predicate-version.ts +++ b/packages/api/src/database/migrations/1714734332092-update-predicate-version.ts @@ -7,7 +7,9 @@ export class updatePredicateVersion1714734332092 implements MigrationInterface { const defaultPredicateVersion = await queryRunner.manager.findOne( PredicateVersion, { - code: predicateVersion.code, + where: { + code: predicateVersion.code, + }, }, ); diff --git a/packages/api/src/database/seeders/110820231840-create-users.ts b/packages/api/src/database/seeders/110820231840-create-users.ts index a7df48345..e059fc4d8 100644 --- a/packages/api/src/database/seeders/110820231840-create-users.ts +++ b/packages/api/src/database/seeders/110820231840-create-users.ts @@ -12,7 +12,15 @@ import { IconUtils } from '@utils/icons'; export default async function () { const users = await generateInitialUsers(); for await (const user of users) { - const _user = await User.create(user).save(); + const _user = await User.create(user) + .save() + .then(async _ => { + return await User.findOne({ + order: { + createdAt: 'DESC', + }, + }); + }); await Workspace.create({ name: `singleWorkspace[${_user.id}]`, diff --git a/packages/api/src/middlewares/auth/index.ts b/packages/api/src/middlewares/auth/index.ts index 96922ee7c..03e43b2b5 100644 --- a/packages/api/src/middlewares/auth/index.ts +++ b/packages/api/src/middlewares/auth/index.ts @@ -63,7 +63,7 @@ async function authMiddleware(req: Request, res: Response, next: NextFunction) { await recover.save(); requestAuth.user = recover.owner; requestAuth.workspace = await Workspace.findOne({ - where: { owner: recover.owner.id, single: true }, // just single workspace + where: { owner: recover.owner, single: true }, // just single workspace }); return next(); diff --git a/packages/api/src/mocks/initialSeeds/initialPredicate.ts b/packages/api/src/mocks/initialSeeds/initialPredicate.ts index cf2c372a9..a7e50f7f2 100644 --- a/packages/api/src/mocks/initialSeeds/initialPredicate.ts +++ b/packages/api/src/mocks/initialSeeds/initialPredicate.ts @@ -30,7 +30,9 @@ export const generateInitialPredicate = async (): Promise> => }, }); const version = await PredicateVersion.findOne({ - code: predicateVersionMock.code, + where: { + code: predicateVersionMock.code, + }, }); const predicate1: Partial = { diff --git a/packages/api/src/modules/auth/controller.ts b/packages/api/src/modules/auth/controller.ts index 6bac58c30..0da381c64 100644 --- a/packages/api/src/modules/auth/controller.ts +++ b/packages/api/src/modules/auth/controller.ts @@ -59,7 +59,7 @@ export class AuthController { try { const { address } = req.params; const { origin } = req.headers; - const owner = await User.findOne({ address: address }); + const owner = await User.findOne({ where: { address } }); const response = await new RecoverCodeService().create({ owner, diff --git a/packages/api/src/modules/dApps/service.ts b/packages/api/src/modules/dApps/service.ts index 8c660882e..994ba5f39 100644 --- a/packages/api/src/modules/dApps/service.ts +++ b/packages/api/src/modules/dApps/service.ts @@ -3,12 +3,16 @@ import { ErrorTypes } from '@src/utils/error'; import Internal from '@src/utils/error/Internal'; import { IDAPPCreatePayload, IDAppsService } from './types'; +import { DeepPartial } from 'typeorm'; export class DAppsService implements IDAppsService { async create(params: IDAPPCreatePayload) { - return await DApp.create(params) + const partialPayload: DeepPartial = params; + return await DApp.create(partialPayload) .save() - .then(data => data) + .then(async () => { + return await DApp.findOne({ order: { createdAt: 'DESC' } }); + }) .catch(e => { throw new Internal({ type: ErrorTypes.Internal, diff --git a/packages/api/src/modules/notification/services.ts b/packages/api/src/modules/notification/services.ts index bf3886792..5a941fb31 100644 --- a/packages/api/src/modules/notification/services.ts +++ b/packages/api/src/modules/notification/services.ts @@ -13,6 +13,8 @@ import { INotificationService, IUpdateNotificationPayload, } from './types'; +import { DeepPartial } from 'typeorm'; +import { VaultTemplate } from '@src/models/VaultTemplate'; export class NotificationService implements INotificationService { private _pagination: PaginationParams; @@ -38,9 +40,10 @@ export class NotificationService implements INotificationService { } async create(payload: ICreateNotificationPayload): Promise { - return await Notification.create(payload) + const partialPayload: DeepPartial = payload; + return await Notification.create(partialPayload) .save() - .then(notification => notification) + .then(() => this.findLast()) .catch(e => { throw new Internal({ type: ErrorTypes.Internal, @@ -94,4 +97,19 @@ export class NotificationService implements INotificationService { }); }); } + + async findLast(): Promise { + return await Notification.createQueryBuilder('notification') + .select() + .orderBy('notification.createdAt', 'DESC') + .getOne() + .then(data => data) + .catch(e => { + throw new Internal({ + type: ErrorTypes.Internal, + title: 'Error on notification find last', + detail: e, + }); + }); + } } diff --git a/packages/api/src/modules/predicate/services.ts b/packages/api/src/modules/predicate/services.ts index 642658609..91ac3e83b 100644 --- a/packages/api/src/modules/predicate/services.ts +++ b/packages/api/src/modules/predicate/services.ts @@ -1,5 +1,4 @@ import { IConfVault, Vault } from 'bakosafe'; -import { Provider } from 'fuels'; import { Brackets } from 'typeorm'; import { NotFound } from '@src/utils/error'; @@ -16,6 +15,10 @@ import { IPredicatePayload, IPredicateService, } from './types'; +import { + Unauthorized, + UnauthorizedErrorTitles, +} from '@src/utils/error/Unauthorized'; export class PredicateService implements IPredicateService { private _ordination: IOrdination = { @@ -55,21 +58,21 @@ export class PredicateService implements IPredicateService { } async create(payload: IPredicatePayload): Promise { - return Predicate.create(payload) - .save() - .then(predicate => predicate) - .catch(e => { - throw new Internal({ - type: ErrorTypes.Internal, - title: 'Error on predicate creation', - detail: e, - }); + try { + const predicate = await Predicate.create(payload).save(); + return predicate; + } catch (e) { + throw new Internal({ + type: ErrorTypes.Internal, + title: 'Error on predicate creation', + detail: e, }); + } } async findById(id: string, signer?: string): Promise { - return ( - Predicate.createQueryBuilder('p') + try { + const predicate = await Predicate.createQueryBuilder('p') .where({ id }) .leftJoinAndSelect('p.members', 'members') .leftJoinAndSelect('p.owner', 'owner') @@ -96,44 +99,28 @@ export class PredicateService implements IPredicateService { 'addressBook.user_id', 'adb_workspace.id', ]) - //.addSelect(['workspace.id', 'workspace.address_book']) - //.innerJoin('workspace.address_book', 'address_book') - // .innerJoin('address_book.user', 'address_book_user') - // .addSelect(['workspace.id', 'address_book.nickname', 'address_book_user.id']) - .getOne() - - .then(predicate => { - const isNotMember = !predicate.members - .map(m => m.address) - .includes(signer); - - // if (isNotMember) { - // throw new Unauthorized({ - // type: ErrorTypes.Unauthorized, - // title: UnauthorizedErrorTitles.INVALID_PERMISSION, - // detail: `You are not authorized to access requested predicate.`, - // }); - // } - - if (!predicate) { - throw new NotFound({ - type: ErrorTypes.NotFound, - title: 'Predicate not found', - detail: `Predicate with id ${id} not found`, - }); - } - return predicate; - }) - .catch(e => { - if (e instanceof GeneralError) throw e; - - throw new Internal({ - type: ErrorTypes.Internal, - title: 'Error on predicate findById', - detail: e, - }); - }) - ); + .getOne(); + + if (!predicate) { + throw new NotFound({ + type: ErrorTypes.NotFound, + title: 'Predicate not found', + detail: `Predicate with id ${id} not found`, + }); + } + + return predicate; + } catch (e) { + if (e instanceof GeneralError) { + throw e; + } + + throw new Internal({ + type: ErrorTypes.Internal, + title: 'Error on predicate findById', + detail: e, + }); + } } async list(): Promise | Predicate[]> { @@ -158,154 +145,159 @@ export class PredicateService implements IPredicateService { 'workspace.avatar', ]); - const handleInternalError = e => { - if (e instanceof GeneralError) throw e; - - throw new Internal({ - type: ErrorTypes.Internal, - title: 'Error on predicate list', - detail: e, - }); - }; - - // todo: - /** - * include inner join to transactions and assets - * return itens - * and filter just assets ID - */ - - this._filter.address && - queryBuilder.andWhere('p.predicateAddress = :predicateAddress', { - predicateAddress: this._filter.address, - }); + try { + // Aplicar filtros + if (this._filter.address) { + queryBuilder.andWhere('p.predicateAddress = :predicateAddress', { + predicateAddress: this._filter.address, + }); + } - this._filter.provider && - queryBuilder.andWhere('LOWER(p.provider) = LOWER(:provider)', { - provider: `${this._filter.provider}`, - }); + if (this._filter.provider) { + queryBuilder.andWhere('LOWER(p.provider) = LOWER(:provider)', { + provider: `${this._filter.provider}`, + }); + } - // =============== specific for workspace =============== - this._filter.workspace && - !this._filter.signer && - queryBuilder.andWhere( - new Brackets(qb => { - if (this._filter.workspace) { + if (this._filter.workspace && !this._filter.signer) { + queryBuilder.andWhere( + new Brackets(qb => { qb.orWhere('workspace.id IN (:...workspace)', { workspace: this._filter.workspace, }); - } - }), - ); + }), + ); + } + + if (this._filter.name) { + queryBuilder.andWhere('p.name = :name', { + name: this._filter.name, + }); + } + + if (this._filter.workspace || this._filter.signer) { + queryBuilder.andWhere( + new Brackets(qb => { + if (this._filter.workspace) { + qb.orWhere('workspace.id IN (:...workspace)', { + workspace: this._filter.workspace, + }); + } + if (this._filter.signer) { + qb.orWhere(subQb => { + const subQuery = subQb + .subQuery() + .select('1') + .from('predicate_members', 'pm') + .where('pm.predicate_id = p.id') + .andWhere( + '(pm.user_id = (SELECT u.id FROM users u WHERE u.address = :signer))', + { signer: this._filter.signer }, + ) + .getQuery(); + return `EXISTS ${subQuery}`; + }); + } + }), + ); + } + + if (this._filter.q) { + queryBuilder.andWhere( + new Brackets(qb => + qb + .where('LOWER(p.name) LIKE LOWER(:name)', { + name: `%${this._filter.q}%`, + }) + .orWhere('LOWER(p.description) LIKE LOWER(:description)', { + description: `%${this._filter.q}%`, + }), + ), + ); + } + + // Aplicar ordenação + if (hasOrdination) { + queryBuilder.orderBy( + `p.${this._ordination.orderBy}`, + this._ordination.sort, + ); + } + + // Paginação + if (hasPagination) { + return await Pagination.create(queryBuilder).paginate(this._pagination); + } else { + const predicates = await queryBuilder.getMany(); + return predicates ?? []; + } + } catch (e) { + if (e instanceof GeneralError) { + throw e; + } - this._filter.name && - queryBuilder.andWhere('p.name = :name', { - name: this._filter.name, + throw new Internal({ + type: ErrorTypes.Internal, + title: 'Error on predicate list', + detail: e, }); + } + } - // =============== specific for home =============== - (this._filter.workspace || this._filter.signer) && - queryBuilder.andWhere( - new Brackets(qb => { - if (this._filter.workspace) { - qb.orWhere('workspace.id IN (:...workspace)', { - workspace: this._filter.workspace, - }); - } - // Se o filtro signer existe - if (this._filter.signer) { - qb.orWhere(subQb => { - const subQuery = subQb - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - //@ts-ignore - .subQuery() - .select('1') - .from('predicate_members', 'pm') - .where('pm.predicate_id = p.id') - .andWhere( - '(pm.user_id = (SELECT u.id FROM users u WHERE u.address = :signer))', - { signer: this._filter.signer }, - ) - .getQuery(); - - return `EXISTS ${subQuery}`; - }); - } - }), - ); - // =============== specific for home =============== - - // this._filter.signer && - // queryBuilder.andWhere(qb => { - // const subQuery = qb - // .subQuery() - // .select('1') - // .from('predicate_members', 'pm') - // .where('pm.predicate_id = p.id') - // .andWhere( - // '(pm.user_id = (SELECT u.id FROM users u WHERE u.address = :signer))', - // { signer: this._filter.signer }, - // ) - // .getQuery(); - - // return `EXISTS ${subQuery}`; - // }); - - this._filter.q && - queryBuilder.andWhere( - new Brackets(qb => - qb - .where('LOWER(p.name) LIKE LOWER(:name)', { - name: `%${this._filter.q}%`, - }) - .orWhere('LOWER(p.description) LIKE LOWER(:description)', { - description: `%${this._filter.q}%`, - }), - ), + async update(id: string, payload?: IPredicatePayload): Promise { + try { + await Predicate.update( + { id }, + { + ...payload, + updatedAt: new Date(), + }, ); - hasOrdination && - queryBuilder.orderBy(`p.${this._ordination.orderBy}`, this._ordination.sort); - - return hasPagination - ? Pagination.create(queryBuilder) - .paginate(this._pagination) - .then(result => result) - .catch(handleInternalError) - : queryBuilder - .getMany() - .then(predicates => predicates ?? []) - .catch(handleInternalError); - } + const updatedPredicate = await this.findById(id); - async update(id: string, payload?: IPredicatePayload): Promise { - return Predicate.update( - { id }, - { - ...payload, - updatedAt: new Date(), - }, - ) - .then(() => this.findById(id)) - .catch(e => { + if (!updatedPredicate) { throw new Internal({ - type: ErrorTypes.Internal, - title: 'Error on predicate update', - detail: e, + type: ErrorTypes.NotFound, + title: 'Predicate not found', + detail: `Predicate with id ${id} not found after update`, }); + } + + return updatedPredicate; + } catch (e) { + throw new Internal({ + type: ErrorTypes.Internal, + title: 'Error on predicate update', + detail: e, }); + } } async delete(id: string): Promise { - return await Predicate.update({ id }, { deletedAt: new Date() }) - .then(() => true) - .catch(() => { + try { + const result = await Predicate.update({ id }, { deletedAt: new Date() }); + + if (result.affected === 0) { throw new NotFound({ type: ErrorTypes.NotFound, title: 'Predicate not found', detail: `Predicate with id ${id} not found`, }); + } + + return true; + } catch (e) { + if (e instanceof NotFound) { + throw e; + } + + throw new Internal({ + type: ErrorTypes.Internal, + title: 'Error on predicate deletion', + detail: e, }); + } } async instancePredicate(predicateId: string): Promise { diff --git a/packages/api/src/modules/predicateVersion/services.ts b/packages/api/src/modules/predicateVersion/services.ts index 460df9bd4..fc23214a1 100644 --- a/packages/api/src/modules/predicateVersion/services.ts +++ b/packages/api/src/modules/predicateVersion/services.ts @@ -106,11 +106,7 @@ export class PredicateVersionService implements IPredicateVersionService { } async findCurrentVersion(): Promise { - return await PredicateVersion.findOne({ - order: { - createdAt: 'DESC', - }, - }) + return await PredicateVersion.findOne({ where: { active: true } }) .then(predicateVersion => { if (!predicateVersion) { throw new NotFound({ diff --git a/packages/api/src/modules/recoverCode/services.ts b/packages/api/src/modules/recoverCode/services.ts index 7103c6038..7367137ab 100644 --- a/packages/api/src/modules/recoverCode/services.ts +++ b/packages/api/src/modules/recoverCode/services.ts @@ -4,46 +4,73 @@ import { ErrorTypes } from '@utils/error/GeneralError'; import Internal from '@utils/error/Internal'; import { IRecoverCodeService, ICreateRecoverCodePayload } from './types'; +import { DeepPartial } from 'typeorm'; export class RecoverCodeService implements IRecoverCodeService { async create(paylaod: ICreateRecoverCodePayload) { - return RecoverCode.create(paylaod) - .save() - .then(data => data) - .catch(e => { - throw new Internal({ - type: ErrorTypes.Create, - title: 'Error on recover code create', - detail: e, - }); + try { + const partialPayload: DeepPartial = paylaod; + await RecoverCode.create(partialPayload).save(); + return this.findLast(); + } catch (e) { + throw new Internal({ + type: ErrorTypes.Create, + title: 'Error on recover code create', + detail: e, }); + } } async update(id: string, payload: Partial) { - const recoverCode = Object.assign(await RecoverCode.findOne({ id }), payload); - return recoverCode - .save() - .then(async () => { - return await RecoverCode.findOne({ id }); - }) - .catch(e => { + try { + const recoverCode = await RecoverCode.findOne({ where: { id } }); + if (!recoverCode) { throw new Internal({ - type: ErrorTypes.Update, - title: 'Error on recover code update', - detail: e, + type: ErrorTypes.NotFound, + title: 'Recover code not found', + detail: `Recover code with ID ${id} not found`, }); + } + + Object.assign(recoverCode, payload); + return await recoverCode.save(); + } catch (e) { + throw new Internal({ + type: ErrorTypes.Update, + title: 'Error on recover code update', + detail: e, }); + } } async findByCode(code: string) { - return RecoverCode.findOne({ where: { code } }) - .then(data => data) - .catch(e => { - throw new Internal({ - type: ErrorTypes.Internal, - title: 'Error on recover code find', - detail: e, - }); + try { + const data = await RecoverCode.findOne({ where: { code } }); + return data; + } catch (e) { + throw new Internal({ + type: ErrorTypes.Internal, + title: 'Error on recover code find', + detail: e, + }); + } + } + + async findLast() { + try { + return await RecoverCode.createQueryBuilder('rc') + .select() + .innerJoin('rc.owner', 'owner') + .addSelect(['owner.id']) + .take(1) + .orderBy('rc.createdAt', 'DESC') + .getOne(); + } catch (e) { + throw new Internal({ + type: ErrorTypes.Internal, + title: 'Error on recover code find last', + detail: e, }); + } } } diff --git a/packages/api/src/modules/transaction/controller.ts b/packages/api/src/modules/transaction/controller.ts index a9874c2cf..137745bb1 100644 --- a/packages/api/src/modules/transaction/controller.ts +++ b/packages/api/src/modules/transaction/controller.ts @@ -525,7 +525,6 @@ export class TransactionController { status: TransactionStatus.FAILED, sendTime: new Date(), }); - console.log('[failed]', e); throw new Error('Transaction send failed'); }); diff --git a/packages/api/src/modules/transaction/services.ts b/packages/api/src/modules/transaction/services.ts index 7d0aaa0bc..79374110b 100644 --- a/packages/api/src/modules/transaction/services.ts +++ b/packages/api/src/modules/transaction/services.ts @@ -126,7 +126,6 @@ export class TransactionService implements ITransactionService { 't.createdAt', 't.gasUsed', 't.hash', - 't.createdAt', 't.id', 't.name', 't.predicateId', @@ -159,6 +158,8 @@ export class TransactionService implements ITransactionService { address: this._filter.predicateAddress, }); + console.log(this._ordination); + // =============== specific for workspace =============== this._filter.workspaceId && !this._filter.signer && @@ -183,14 +184,6 @@ export class TransactionService implements ITransactionService { workspace: this._filter.workspaceId, }); } - // Uncomment this to not show workspace transactions in the single. - // if (this._filter.signer) { - // qb.orWhere(subQb => { - // subQb.where('witnesses.account = :signer', { - // signer: this._filter.signer, - // }); - // }); - // } if (this._filter.signer) { qb.orWhere('members.address = :signer', { diff --git a/packages/api/src/modules/user/controller.ts b/packages/api/src/modules/user/controller.ts index 519ada219..187ef814a 100644 --- a/packages/api/src/modules/user/controller.ts +++ b/packages/api/src/modules/user/controller.ts @@ -144,7 +144,7 @@ export class UserController { if (!existingUser) { //verify name exists - const existingName = await User.findOne({ name }); + const existingName = await User.findOne({ where: { name } }); if (existingName) { throw new BadRequest({ type: ErrorTypes.Create, diff --git a/packages/api/src/modules/vaultTemplate/services.ts b/packages/api/src/modules/vaultTemplate/services.ts index d16b310e0..d0acca32e 100644 --- a/packages/api/src/modules/vaultTemplate/services.ts +++ b/packages/api/src/modules/vaultTemplate/services.ts @@ -12,6 +12,7 @@ import { IVaultTemplateService, IUpdatePayload, } from './types'; +import { DeepPartial } from 'typeorm'; export class VaultTemplateService implements IVaultTemplateService { private _ordination: IOrdination = { @@ -36,9 +37,10 @@ export class VaultTemplateService implements IVaultTemplateService { } async create(payload: ICreatePayload): Promise { - return await VaultTemplate.create(payload) + const partialPayload: DeepPartial = payload; + return await VaultTemplate.create(partialPayload) .save() - .then(template => template) + .then(() => this.findLast()) .catch(e => { throw new Internal({ type: ErrorTypes.Internal, @@ -124,4 +126,8 @@ export class VaultTemplateService implements IVaultTemplateService { }) .catch(handleInternalError); } + + async findLast(): Promise { + return await VaultTemplate.findOne({ order: { createdAt: 'DESC' } }); + } } diff --git a/packages/api/src/modules/workspace/controller.ts b/packages/api/src/modules/workspace/controller.ts index 0f521ae91..5bf0ecf8f 100644 --- a/packages/api/src/modules/workspace/controller.ts +++ b/packages/api/src/modules/workspace/controller.ts @@ -76,7 +76,7 @@ export class WorkspaceController { const predicateService = new PredicateService(); const balance = await Predicate.find({ where: { - workspace: workspace.id, + workspace: workspace, }, select: ['id'], }).then(async (response: Predicate[]) => { diff --git a/packages/api/src/modules/workspace/services.ts b/packages/api/src/modules/workspace/services.ts index cf8ac6d1c..ee3a06adb 100644 --- a/packages/api/src/modules/workspace/services.ts +++ b/packages/api/src/modules/workspace/services.ts @@ -116,22 +116,28 @@ export class WorkspaceService implements IWorkspaceService { } async create(payload: Partial): Promise { - return await Workspace.create(payload) - .save() - .then(data => data) - .catch(error => { - if (error instanceof GeneralError) throw error; + try { + // Criar e salvar o Workspace + await Workspace.create(payload).save(); + return this.findLast(); + } catch (error) { + if (error instanceof GeneralError) { + throw error; + } - throw new Internal({ - type: ErrorTypes.Create, - title: 'Error on workspace create', - detail: error, - }); + throw new Internal({ + type: ErrorTypes.Create, + title: 'Error on workspace create', + detail: error, }); + } } async update(payload: Partial): Promise { - const w = Object.assign(await Workspace.findOne({ id: payload.id }), payload); + const w = Object.assign( + await Workspace.findOne({ where: { id: payload.id } }), + payload, + ); return w .save() @@ -223,7 +229,7 @@ export class WorkspaceService implements IWorkspaceService { predicate: string, worksapce: string, ): Promise { - return await Workspace.findOne({ id: worksapce }) + return await Workspace.findOne({ where: { id: worksapce } }) .then(async workspace => { const p = workspace.permissions; signers.map(s => { @@ -289,4 +295,20 @@ export class WorkspaceService implements IWorkspaceService { }; }); } + + async findLast() { + try { + const data = await Workspace.find({ + order: { createdAt: 'DESC' }, + relations: ['owner', 'members'], + }); + return data[0]; + } catch (e) { + throw new Internal({ + type: ErrorTypes.Internal, + title: 'Error on workspace find', + detail: e, + }); + } + } } diff --git a/packages/api/src/utils/error/Unauthorized.ts b/packages/api/src/utils/error/Unauthorized.ts index 93d54c2d1..ce087c057 100644 --- a/packages/api/src/utils/error/Unauthorized.ts +++ b/packages/api/src/utils/error/Unauthorized.ts @@ -1,14 +1,5 @@ import GeneralError, { Error } from './GeneralError'; -export enum ErrorTypes { - Create = 'CreateException', - Update = 'UpdateException', - Delete = 'DeleteException', - NotFound = 'NotFound', - Unauthorized = 'Unauthorized', - Internal = 'Internal', -} - export enum UnauthorizedErrorTitles { MISSING_CREDENTIALS = 'Missing credentials', INVALID_CREDENTIALS = 'Invalid credentials', diff --git a/packages/api/src/utils/error/index.ts b/packages/api/src/utils/error/index.ts index b18aa83ab..9b54dfce3 100644 --- a/packages/api/src/utils/error/index.ts +++ b/packages/api/src/utils/error/index.ts @@ -1,6 +1,9 @@ export { default as BadRequest } from './BadRequest'; export * from './GeneralError'; export { default as NotFound } from './NotFound'; +export * from './Forbidden'; +export * from './Unauthorized'; +export { default as Internal } from './Internal'; export enum Responses { BadRequest = 400, diff --git a/packages/api/src/utils/token/utils.ts b/packages/api/src/utils/token/utils.ts index d168e2b73..9aece3ead 100644 --- a/packages/api/src/utils/token/utils.ts +++ b/packages/api/src/utils/token/utils.ts @@ -74,7 +74,7 @@ export class TokenUtils { return user; } - static async invalidateRecoverCode(user: string, type) { + static async invalidateRecoverCode(user: User, type) { const recoverCode = await RecoverCode.findOne({ where: { owner: user, type }, order: { createdAt: 'DESC' }, @@ -172,7 +172,7 @@ export class TokenUtils { const user = await TokenUtils.checkUserExists(address); - await TokenUtils.invalidateRecoverCode(user.id, RecoverCodeType.AUTH); + await TokenUtils.invalidateRecoverCode(user, RecoverCodeType.AUTH); const workspace = await TokenUtils.findSingleWorkspace(user.id); await TokenUtils.revokeToken(user); // todo: verify if it's necessary From 626d6aa310a798de4e98366edd9c4fb7080375e7 Mon Sep 17 00:00:00 2001 From: guimroque Date: Wed, 12 Jun 2024 15:56:34 -0300 Subject: [PATCH 02/11] fix: increase typeorm version --- packages/database/docker-compose.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/database/docker-compose.yml b/packages/database/docker-compose.yml index f734d263e..070f8b111 100644 --- a/packages/database/docker-compose.yml +++ b/packages/database/docker-compose.yml @@ -2,7 +2,7 @@ version: '3' services: db: container_name: ${DATABASE_ENVIRONMENT} - image: postgres + image: postgres:16.3-alpine3.20 environment: POSTGRES_DB: ${DATABASE_NAME} POSTGRES_USER: ${DATABASE_USERNAME} From 565b27a52b23130174e8565a049e4615324282d8 Mon Sep 17 00:00:00 2001 From: guimroque Date: Wed, 12 Jun 2024 16:03:43 -0300 Subject: [PATCH 03/11] chore: lastItem --- packages/api/src/modules/vaultTemplate/services.ts | 14 +++++++++++++- packages/api/src/modules/workspace/services.ts | 11 ++++++----- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/packages/api/src/modules/vaultTemplate/services.ts b/packages/api/src/modules/vaultTemplate/services.ts index d0acca32e..617e0f1d7 100644 --- a/packages/api/src/modules/vaultTemplate/services.ts +++ b/packages/api/src/modules/vaultTemplate/services.ts @@ -128,6 +128,18 @@ export class VaultTemplateService implements IVaultTemplateService { } async findLast(): Promise { - return await VaultTemplate.findOne({ order: { createdAt: 'DESC' } }); + try { + return await VaultTemplate.createQueryBuilder('t') + .select() + .take(1) + .orderBy('t.createdAt', 'DESC') + .getOne(); + } catch (e) { + throw new Internal({ + type: ErrorTypes.Internal, + title: 'Error on vault template find last', + detail: e, + }); + } } } diff --git a/packages/api/src/modules/workspace/services.ts b/packages/api/src/modules/workspace/services.ts index ee3a06adb..d8d6ca3d7 100644 --- a/packages/api/src/modules/workspace/services.ts +++ b/packages/api/src/modules/workspace/services.ts @@ -298,11 +298,12 @@ export class WorkspaceService implements IWorkspaceService { async findLast() { try { - const data = await Workspace.find({ - order: { createdAt: 'DESC' }, - relations: ['owner', 'members'], - }); - return data[0]; + return await Workspace.createQueryBuilder('w') + .innerJoinAndSelect('w.owner', 'owner') + .innerJoinAndSelect('w.members', 'members') + .orderBy('w.createdAt', 'DESC') + .take(1) + .getOne(); } catch (e) { throw new Internal({ type: ErrorTypes.Internal, From 494c985d4a9d22e60fae31d1b84ccdf8dbd9af76 Mon Sep 17 00:00:00 2001 From: guimroque Date: Wed, 12 Jun 2024 16:17:53 -0300 Subject: [PATCH 04/11] chore: remove log --- packages/api/src/modules/transaction/services.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/api/src/modules/transaction/services.ts b/packages/api/src/modules/transaction/services.ts index 79374110b..84b1332f0 100644 --- a/packages/api/src/modules/transaction/services.ts +++ b/packages/api/src/modules/transaction/services.ts @@ -158,8 +158,6 @@ export class TransactionService implements ITransactionService { address: this._filter.predicateAddress, }); - console.log(this._ordination); - // =============== specific for workspace =============== this._filter.workspaceId && !this._filter.signer && From bfe69a142b53d7cca09342d838650318ec29ca3a Mon Sep 17 00:00:00 2001 From: guimroque Date: Wed, 12 Jun 2024 16:44:12 -0300 Subject: [PATCH 05/11] fix: complement return of create dapp --- packages/api/src/modules/dApps/controller.ts | 2 ++ packages/api/src/modules/dApps/service.ts | 36 +++++++++----------- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/packages/api/src/modules/dApps/controller.ts b/packages/api/src/modules/dApps/controller.ts index ccaec3ce8..318ca7c40 100644 --- a/packages/api/src/modules/dApps/controller.ts +++ b/packages/api/src/modules/dApps/controller.ts @@ -43,6 +43,7 @@ export class DappController { currentVault: predicate, user, }); + console.log('[DAPP]: ', dapp); } const isIncludedVault = dapp.vaults.find(v => v.id === vaultId); @@ -71,6 +72,7 @@ export class DappController { return successful(true, Responses.Created); } catch (e) { + console.log('[ERRO AO CRIAR]: ', e); return error(e.error, e.statusCode); } } diff --git a/packages/api/src/modules/dApps/service.ts b/packages/api/src/modules/dApps/service.ts index 994ba5f39..81829f77b 100644 --- a/packages/api/src/modules/dApps/service.ts +++ b/packages/api/src/modules/dApps/service.ts @@ -10,9 +10,7 @@ export class DAppsService implements IDAppsService { const partialPayload: DeepPartial = params; return await DApp.create(partialPayload) .save() - .then(async () => { - return await DApp.findOne({ order: { createdAt: 'DESC' } }); - }) + .then(() => this.findLast()) .catch(e => { throw new Internal({ type: ErrorTypes.Internal, @@ -67,20 +65,20 @@ export class DAppsService implements IDAppsService { }); } - // async checkExist(address: string, sessionId, url: string) { - // return await DApp.createQueryBuilder('d') - // .innerJoin('d.users', 'users') - // .where('users.address = :address', { address }) - // .andWhere('d.session_id = :sessionId', { sessionId }) - // .andWhere('d.url = :url', { url }) - // .getOne() - // .then(data => data) - // .catch(e => { - // throw new Internal({ - // type: ErrorTypes.Internal, - // title: 'Error on find active sessions to dapp', - // detail: e, - // }); - // }); - // } + async findLast() { + try { + return await DApp.createQueryBuilder('d') + .select() + .innerJoinAndSelect('d.vaults', 'vaults') + .innerJoinAndSelect('d.currentVault', 'currentVault') + .orderBy('d.createdAt', 'DESC') + .getOne(); + } catch (e) { + throw new Internal({ + type: ErrorTypes.Internal, + title: 'Error on find last dapp', + detail: e, + }); + } + } } From 591b50e58ea6f38124be926a64fe431813950b77 Mon Sep 17 00:00:00 2001 From: guimroque Date: Wed, 12 Jun 2024 16:57:31 -0300 Subject: [PATCH 06/11] fix: last item --- packages/api/src/modules/predicateVersion/services.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/api/src/modules/predicateVersion/services.ts b/packages/api/src/modules/predicateVersion/services.ts index fc23214a1..1f9ed3d7e 100644 --- a/packages/api/src/modules/predicateVersion/services.ts +++ b/packages/api/src/modules/predicateVersion/services.ts @@ -106,7 +106,10 @@ export class PredicateVersionService implements IPredicateVersionService { } async findCurrentVersion(): Promise { - return await PredicateVersion.findOne({ where: { active: true } }) + return await PredicateVersion.findOne({ + where: { active: true }, + order: { updatedAt: 'DESC' }, + }) .then(predicateVersion => { if (!predicateVersion) { throw new NotFound({ From 4831ccad2ca01188eb832d1ec4befed67334e3c6 Mon Sep 17 00:00:00 2001 From: guimroque Date: Wed, 12 Jun 2024 16:58:56 -0300 Subject: [PATCH 07/11] fix: error return --- packages/api/src/modules/recoverCode/services.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/api/src/modules/recoverCode/services.ts b/packages/api/src/modules/recoverCode/services.ts index 7367137ab..887e98aa1 100644 --- a/packages/api/src/modules/recoverCode/services.ts +++ b/packages/api/src/modules/recoverCode/services.ts @@ -5,6 +5,7 @@ import Internal from '@utils/error/Internal'; import { IRecoverCodeService, ICreateRecoverCodePayload } from './types'; import { DeepPartial } from 'typeorm'; +import { NotFound } from '@src/utils/error'; export class RecoverCodeService implements IRecoverCodeService { async create(paylaod: ICreateRecoverCodePayload) { @@ -25,7 +26,7 @@ export class RecoverCodeService implements IRecoverCodeService { try { const recoverCode = await RecoverCode.findOne({ where: { id } }); if (!recoverCode) { - throw new Internal({ + throw new NotFound({ type: ErrorTypes.NotFound, title: 'Recover code not found', detail: `Recover code with ID ${id} not found`, @@ -35,6 +36,8 @@ export class RecoverCodeService implements IRecoverCodeService { Object.assign(recoverCode, payload); return await recoverCode.save(); } catch (e) { + if (e instanceof NotFound) throw e; + throw new Internal({ type: ErrorTypes.Update, title: 'Error on recover code update', From ab1747efad244c2b87f3a9ca607e25f1b5ff21b8 Mon Sep 17 00:00:00 2001 From: guimroque Date: Wed, 12 Jun 2024 16:59:52 -0300 Subject: [PATCH 08/11] fix: remove log --- packages/api/src/modules/dApps/controller.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/api/src/modules/dApps/controller.ts b/packages/api/src/modules/dApps/controller.ts index 318ca7c40..fc645a405 100644 --- a/packages/api/src/modules/dApps/controller.ts +++ b/packages/api/src/modules/dApps/controller.ts @@ -43,7 +43,6 @@ export class DappController { currentVault: predicate, user, }); - console.log('[DAPP]: ', dapp); } const isIncludedVault = dapp.vaults.find(v => v.id === vaultId); From 44d7f35ddc9b958f760b119e743a51805d657fe3 Mon Sep 17 00:00:00 2001 From: guimroque Date: Wed, 12 Jun 2024 17:05:44 -0300 Subject: [PATCH 09/11] fix: returned error on predicate update --- packages/api/src/modules/predicate/services.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/api/src/modules/predicate/services.ts b/packages/api/src/modules/predicate/services.ts index 91ac3e83b..ac6289643 100644 --- a/packages/api/src/modules/predicate/services.ts +++ b/packages/api/src/modules/predicate/services.ts @@ -257,7 +257,7 @@ export class PredicateService implements IPredicateService { const updatedPredicate = await this.findById(id); if (!updatedPredicate) { - throw new Internal({ + throw new NotFound({ type: ErrorTypes.NotFound, title: 'Predicate not found', detail: `Predicate with id ${id} not found after update`, @@ -266,6 +266,7 @@ export class PredicateService implements IPredicateService { return updatedPredicate; } catch (e) { + if (e instanceof NotFound) throw e; throw new Internal({ type: ErrorTypes.Internal, title: 'Error on predicate update', From 398005cf6fbbae3f83806ae833087475c3a8511a Mon Sep 17 00:00:00 2001 From: guimroque Date: Wed, 12 Jun 2024 20:19:06 -0300 Subject: [PATCH 10/11] fix: transaction request performance --- packages/api/src/modules/transaction/services.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/api/src/modules/transaction/services.ts b/packages/api/src/modules/transaction/services.ts index 84b1332f0..c44789889 100644 --- a/packages/api/src/modules/transaction/services.ts +++ b/packages/api/src/modules/transaction/services.ts @@ -119,6 +119,8 @@ export class TransactionService implements ITransactionService { }); } + //todo: melhorar a valocidade de processamento dessa query + //caso trocar inner por left atrapalha muito a performance async list(): Promise | Transaction[]> { const hasPagination = this._pagination?.page && this._pagination?.perPage; const queryBuilder = Transaction.createQueryBuilder('t') @@ -135,8 +137,8 @@ export class TransactionService implements ITransactionService { 't.summary', 't.updatedAt', ]) - .leftJoinAndSelect('t.assets', 'assets') - .innerJoin('t.witnesses', 'witnesses') + .leftJoin('t.assets', 'assets') + .leftJoin('t.witnesses', 'witnesses') .innerJoin('t.predicate', 'predicate') .addSelect([ 'predicate.name', @@ -147,6 +149,10 @@ export class TransactionService implements ITransactionService { 'witnesses.account', 'witnesses.signature', 'witnesses.status', + 'assets.id', + 'assets.amount', + 'assets.to', + 'assets.assetId', ]) .innerJoin('predicate.members', 'members') .addSelect(['members.id', 'members.avatar', 'members.address']) From ada59346f50b1f80936daba52d6038af4ae34dc4 Mon Sep 17 00:00:00 2001 From: guimroque Date: Wed, 12 Jun 2024 20:29:34 -0300 Subject: [PATCH 11/11] fix: tx quary --- packages/api/src/modules/transaction/services.ts | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/packages/api/src/modules/transaction/services.ts b/packages/api/src/modules/transaction/services.ts index c44789889..0c7338351 100644 --- a/packages/api/src/modules/transaction/services.ts +++ b/packages/api/src/modules/transaction/services.ts @@ -139,7 +139,9 @@ export class TransactionService implements ITransactionService { ]) .leftJoin('t.assets', 'assets') .leftJoin('t.witnesses', 'witnesses') - .innerJoin('t.predicate', 'predicate') + .leftJoin('t.predicate', 'predicate') + .leftJoin('predicate.members', 'members') + .leftJoin('predicate.workspace', 'workspace') .addSelect([ 'predicate.name', 'predicate.id', @@ -153,11 +155,13 @@ export class TransactionService implements ITransactionService { 'assets.amount', 'assets.to', 'assets.assetId', - ]) - .innerJoin('predicate.members', 'members') - .addSelect(['members.id', 'members.avatar', 'members.address']) - .innerJoin('predicate.workspace', 'workspace') - .addSelect(['workspace.id', 'workspace.name', 'workspace.single']); + 'members.id', + 'members.avatar', + 'members.address', + 'workspace.id', + 'workspace.name', + 'workspace.single', + ]); this._filter.predicateAddress && queryBuilder.andWhere('predicate.predicateAddress = :address', {