chore(*): remove unused code (#6781)

The code removed in the PR was flagged as unused by the JetBrains
inspector.

I did a QA on the dev environment but other checks are highly
recommended.

There is one commit by scope to make the review easier.

---------

Co-authored-by: Charles Bochet <charles@twenty.com>
This commit is contained in:
Antoine Moreaux
2024-08-29 18:16:50 +02:00
committed by GitHub
parent ebfdc6cfd2
commit cd06ae20e8
86 changed files with 97 additions and 575 deletions

View File

@ -351,6 +351,7 @@ export type Mutation = {
deleteOneServerlessFunction: ServerlessFunction;
deleteUser: User;
disablePostgresProxy: PostgresCredentials;
disableWorkflowTrigger: Scalars['Boolean'];
emailPasswordResetLink: EmailPasswordResetLink;
enablePostgresProxy: PostgresCredentials;
enableWorkflowTrigger: Scalars['Boolean'];
@ -431,6 +432,11 @@ export type MutationDeleteOneServerlessFunctionArgs = {
};
export type MutationDisableWorkflowTriggerArgs = {
workflowVersionId: Scalars['String'];
};
export type MutationEmailPasswordResetLinkArgs = {
email: Scalars['String'];
};
@ -1186,6 +1192,7 @@ export type Field = {
isSystem?: Maybe<Scalars['Boolean']>;
label: Scalars['String'];
name: Scalars['String'];
object?: Maybe<Object>;
options?: Maybe<Scalars['JSON']>;
relationDefinition?: Maybe<RelationDefinition>;
settings?: Maybe<Scalars['JSON']>;

View File

@ -121,11 +121,13 @@ export const useRecordActionBar = ({
title={`Delete ${numberOfSelectedRecords} ${
numberOfSelectedRecords === 1 ? `record` : 'records'
}`}
subtitle={`This action cannot be undone. This will permanently delete ${
subtitle={`Are you sure you want to delete ${
numberOfSelectedRecords === 1
? 'this record'
: 'these records'
}`}
}? ${
numberOfSelectedRecords === 1 ? 'It' : 'They'
} can be recovered from the Options menu.`}
onConfirmClick={() => handleDeleteClick()}
deleteButtonText={`Delete ${
numberOfSelectedRecords > 1 ? 'Records' : 'Record'

View File

@ -52,7 +52,7 @@ export const useHandleToggleTrashColumnFilter = ({
operand: ViewFilterOperand.IsNotEmpty,
displayValue: '',
definition: {
label: 'Trash',
label: `Deleted ${objectNameSingular}`,
iconName: 'IconTrash',
fieldMetadataId: trashFieldMetadata.id,
type: filterType,
@ -61,7 +61,12 @@ export const useHandleToggleTrashColumnFilter = ({
};
upsertCombinedViewFilter(newFilter);
}, [columnDefinitions, objectMetadataItem.fields, upsertCombinedViewFilter]);
}, [
columnDefinitions,
objectMetadataItem.fields,
objectNameSingular,
upsertCombinedViewFilter,
]);
return handleToggleTrashColumnFilter;
};

View File

@ -166,7 +166,7 @@ export const RecordIndexOptionsDropdownContent = ({
closeDropdown();
}}
LeftIcon={IconTrash}
text="Trash"
text={`Deleted ${objectNameSingular}`}
/>
</DropdownMenuItemsContainer>
)}

View File

@ -1,3 +1,4 @@
/* eslint-disable no-console */
import react from '@vitejs/plugin-react-swc';
import wyw from '@wyw-in-js/vite';
import path from 'path';
@ -8,13 +9,9 @@ import tsconfigPaths from 'vite-tsconfig-paths';
type Checkers = Parameters<typeof checker>[0];
// https://vitejs.dev/config/
export default defineConfig(({ command, mode }) => {
const env = loadEnv(mode, process.cwd(), '');
/*
Using explicit env variables, there is no need to expose all of them (security).
*/
const {
REACT_APP_SERVER_BASE_URL,
VITE_BUILD_SOURCEMAP,

View File

@ -1,21 +1,9 @@
import { DataSource } from 'typeorm';
import {
seedUsers,
deleteUsersByWorkspace,
} from 'src/database/typeorm-seeds/core/users';
import {
seedWorkspaces,
deleteWorkspaces,
} from 'src/database/typeorm-seeds/core/workspaces';
import {
seedFeatureFlags,
deleteFeatureFlags,
} from 'src/database/typeorm-seeds/core/feature-flags';
import {
deleteUserWorkspaces,
seedUserWorkspaces,
} from 'src/database/typeorm-seeds/core/userWorkspaces';
import { seedUsers } from 'src/database/typeorm-seeds/core/users';
import { seedWorkspaces } from 'src/database/typeorm-seeds/core/workspaces';
import { seedFeatureFlags } from 'src/database/typeorm-seeds/core/feature-flags';
import { seedUserWorkspaces } from 'src/database/typeorm-seeds/core/userWorkspaces';
export const seedCoreSchema = async (
workspaceDataSource: DataSource,
@ -28,16 +16,3 @@ export const seedCoreSchema = async (
await seedUserWorkspaces(workspaceDataSource, schemaName, workspaceId);
await seedFeatureFlags(workspaceDataSource, schemaName, workspaceId);
};
export const deleteCoreSchema = async (
workspaceDataSource: DataSource,
workspaceId: string,
) => {
const schemaName = 'core';
await deleteUserWorkspaces(workspaceDataSource, schemaName, workspaceId);
await deleteUsersByWorkspace(workspaceDataSource, schemaName, workspaceId);
await deleteFeatureFlags(workspaceDataSource, schemaName, workspaceId);
// deleteWorkspaces should be last
await deleteWorkspaces(workspaceDataSource, schemaName, workspaceId);
};

View File

@ -75,9 +75,6 @@ export class GraphQLConfigService
const data = await this.tokenService.validateToken(context.req);
user = data.user;
workspace = data.workspace;
return await this.createSchema(context, data);
} catch (error) {
if (error instanceof UnauthorizedException) {

View File

@ -1,4 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { v4 as uuidv4 } from 'uuid';
@ -14,8 +14,6 @@ import { FieldsStringFactory } from './fields-string.factory';
@Injectable()
export class CreateManyQueryFactory {
private readonly logger = new Logger(CreateManyQueryFactory.name);
constructor(
private readonly fieldsStringFactory: FieldsStringFactory,
private readonly argsAliasFactory: ArgsAliasFactory,

View File

@ -1,4 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { WorkspaceQueryBuilderOptions } from 'src/engine/api/graphql/workspace-query-builder/interfaces/workspace-query-builder-options.interface';
import { DeleteOneResolverArgs } from 'src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface';
@ -9,8 +9,6 @@ import { FieldsStringFactory } from './fields-string.factory';
@Injectable()
export class DeleteOneQueryFactory {
private readonly logger = new Logger(DeleteOneQueryFactory.name);
constructor(private readonly fieldsStringFactory: FieldsStringFactory) {}
async create(

View File

@ -1,4 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { GraphQLResolveInfo } from 'graphql';
import graphqlFields from 'graphql-fields';
@ -15,8 +15,6 @@ import { RelationFieldAliasFactory } from './relation-field-alias.factory';
@Injectable()
export class FieldsStringFactory {
private readonly logger = new Logger(FieldsStringFactory.name);
constructor(
private readonly fieldAliasFactory: FieldAliasFactory,
private readonly relationFieldAliasFactory: RelationFieldAliasFactory,

View File

@ -1,4 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import isEmpty from 'lodash.isempty';
@ -15,8 +15,6 @@ import { FieldsStringFactory } from './fields-string.factory';
@Injectable()
export class FindDuplicatesQueryFactory {
private readonly logger = new Logger(FindDuplicatesQueryFactory.name);
constructor(
private readonly fieldsStringFactory: FieldsStringFactory,
private readonly argsAliasFactory: ArgsAliasFactory,

View File

@ -1,4 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import {
RecordFilter,
@ -14,8 +14,6 @@ import { FieldsStringFactory } from './fields-string.factory';
@Injectable()
export class FindManyQueryFactory {
private readonly logger = new Logger(FindManyQueryFactory.name);
constructor(
private readonly fieldsStringFactory: FieldsStringFactory,
private readonly argsStringFactory: ArgsStringFactory,

View File

@ -1,4 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { WorkspaceQueryBuilderOptions } from 'src/engine/api/graphql/workspace-query-builder/interfaces/workspace-query-builder-options.interface';
import { RecordFilter } from 'src/engine/api/graphql/workspace-query-builder/interfaces/record.interface';
@ -11,8 +11,6 @@ import { FieldsStringFactory } from './fields-string.factory';
@Injectable()
export class FindOneQueryFactory {
private readonly logger = new Logger(FindOneQueryFactory.name);
constructor(
private readonly fieldsStringFactory: FieldsStringFactory,
private readonly argsStringFactory: ArgsStringFactory,

View File

@ -1,4 +1,4 @@
import { forwardRef, Inject, Injectable, Logger } from '@nestjs/common';
import { forwardRef, Inject, Injectable } from '@nestjs/common';
import { GraphQLResolveInfo } from 'graphql';
@ -20,8 +20,6 @@ import { ArgsStringFactory } from './args-string.factory';
@Injectable()
export class RelationFieldAliasFactory {
private logger = new Logger(RelationFieldAliasFactory.name);
constructor(
@Inject(forwardRef(() => FieldsStringFactory))
private readonly fieldsStringFactory: CircularDep<FieldsStringFactory>,

View File

@ -1,4 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { Record as IRecord } from 'src/engine/api/graphql/workspace-query-builder/interfaces/record.interface';
import { WorkspaceQueryBuilderOptions } from 'src/engine/api/graphql/workspace-query-builder/interfaces/workspace-query-builder-options.interface';
@ -12,8 +12,6 @@ import { FieldsStringFactory } from './fields-string.factory';
@Injectable()
export class UpdateOneQueryFactory {
private readonly logger = new Logger(UpdateOneQueryFactory.name);
constructor(
private readonly fieldsStringFactory: FieldsStringFactory,
private readonly argsAliasFactory: ArgsAliasFactory,

View File

@ -1,4 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { WorkspaceQueryBuilderOptions } from 'src/engine/api/graphql/workspace-query-builder/interfaces/workspace-query-builder-options.interface';
import {
@ -34,8 +34,6 @@ import { FindDuplicatesQueryFactory } from './factories/find-duplicates-query.fa
@Injectable()
export class WorkspaceQueryBuilderFactory {
private readonly logger = new Logger(WorkspaceQueryBuilderFactory.name);
constructor(
private readonly findManyQueryFactory: FindManyQueryFactory,
private readonly findOneQueryFactory: FindOneQueryFactory,

View File

@ -1,12 +1,12 @@
import { TestingModule, Test } from '@nestjs/testing';
import { Test, TestingModule } from '@nestjs/testing';
import { WorkspaceDataSourceService } from 'src/engine/workspace-datasource/workspace-datasource.service';
import { RecordPositionQueryFactory } from 'src/engine/api/graphql/workspace-query-builder/factories/record-position-query.factory';
import { RecordPositionFactory } from 'src/engine/api/graphql/workspace-query-runner/factories/record-position.factory';
import { WorkspaceDataSourceService } from 'src/engine/workspace-datasource/workspace-datasource.service';
describe('RecordPositionFactory', () => {
const recordPositionQueryFactory = {
create: jest.fn().mockResolvedValue('query'),
create: jest.fn().mockReturnValue(['query', []]),
};
let workspaceDataSourceService;

View File

@ -134,7 +134,7 @@ export class QueryRunnerArgsFactory {
),
];
case FieldMetadataType.NUMBER:
return [key, await Promise.resolve(Number(value))];
return [key, Number(value)];
default:
return [key, await Promise.resolve(value)];
}

View File

@ -64,7 +64,7 @@ export class RecordPositionFactory {
dataSourceSchema: string,
workspaceId: string,
) {
const [query, params] = await this.recordPositionQueryFactory.create(
const [query, params] = this.recordPositionQueryFactory.create(
recordPositionQueryArgs,
objectMetadata,
dataSourceSchema,

View File

@ -66,10 +66,4 @@ export class WorkspaceQueryHookStorage {
this.postHookInstances.get(key)?.push(data);
}
getWorkspaceQueryPostHookInstances(
key: WorkspaceQueryHookKey,
): WorkspaceQueryHookData<WorkspaceQueryHookInstance>[] | undefined {
return this.postHookInstances.get(key);
}
}

View File

@ -9,7 +9,7 @@ import { WorkspaceQueryHookOptions } from 'src/engine/api/graphql/workspace-quer
export class WorkspaceQueryHookMetadataAccessor {
constructor(private readonly reflector: Reflector) {}
isWorkspaceQueryHook(target: Type<any> | Function): boolean {
isWorkspaceQueryHook(target: Type | Function): boolean {
if (!target) {
return false;
}
@ -18,7 +18,7 @@ export class WorkspaceQueryHookMetadataAccessor {
}
getWorkspaceQueryHookMetadata(
target: Type<any> | Function,
target: Type | Function,
): WorkspaceQueryHookOptions | undefined {
return this.reflector.get(WORKSPACE_QUERY_HOOK_METADATA, target);
}

View File

@ -1011,17 +1011,6 @@ export class WorkspaceQueryRunnerService {
return parseResult(resultWithGetters);
}
async executeAndParse<Result>(
query: string,
objectMetadataItem: ObjectMetadataInterface,
command: string,
workspaceId: string,
): Promise<Result> {
const result = await this.execute(query, workspaceId);
return this.parseResult(result, objectMetadataItem, command, workspaceId);
}
async triggerWebhooks<Record>(
jobsData: Record[] | undefined,
operation: CallWebhookJobsJobOperation,

View File

@ -1,4 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { GraphQLFieldConfigMap, GraphQLInt, GraphQLObjectType } from 'graphql';
@ -20,8 +20,6 @@ export enum ConnectionTypeDefinitionKind {
@Injectable()
export class ConnectionTypeDefinitionFactory {
private readonly logger = new Logger(ConnectionTypeDefinitionFactory.name);
constructor(private readonly connectionTypeFactory: ConnectionTypeFactory) {}
public create(

View File

@ -1,4 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { GraphQLFieldConfigMap, GraphQLObjectType } from 'graphql';
@ -20,8 +20,6 @@ export enum EdgeTypeDefinitionKind {
@Injectable()
export class EdgeTypeDefinitionFactory {
private readonly logger = new Logger(EdgeTypeDefinitionFactory.name);
constructor(private readonly edgeTypeFactory: EdgeTypeFactory) {}
public create(

View File

@ -1,18 +0,0 @@
import { GraphQLInputObjectType, GraphQLList, GraphQLNonNull } from 'graphql';
import { FilterIs } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/input/filter-is.input-type';
import { DateTimeScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
export const DatetimeFilterType = new GraphQLInputObjectType({
name: 'DateTimeFilter',
fields: {
eq: { type: DateTimeScalarType },
gt: { type: DateTimeScalarType },
gte: { type: DateTimeScalarType },
in: { type: new GraphQLList(new GraphQLNonNull(DateTimeScalarType)) },
lt: { type: DateTimeScalarType },
lte: { type: DateTimeScalarType },
neq: { type: DateTimeScalarType },
is: { type: FilterIs },
},
});

View File

@ -2,10 +2,7 @@ export * from './big-float-filter.input-type';
export * from './big-int-filter.input-type';
export * from './boolean-filter.input-type';
export * from './date-filter.input-type';
export * from './date-time-filter.input-type';
export * from './float-filter.input-type';
export * from './int-filter.input-type';
export * from './raw-json-filter.input-type';
export * from './string-filter.input-type';
export * from './time-filter.input-type';
export * from './uuid-filter.input-type';

View File

@ -1,18 +0,0 @@
import { GraphQLInputObjectType, GraphQLList, GraphQLNonNull } from 'graphql';
import { FilterIs } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/input/filter-is.input-type';
import { TimeScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
export const TimeFilterType = new GraphQLInputObjectType({
name: 'TimeFilter',
fields: {
eq: { type: TimeScalarType },
gt: { type: TimeScalarType },
gte: { type: TimeScalarType },
in: { type: new GraphQLList(new GraphQLNonNull(TimeScalarType)) },
lt: { type: TimeScalarType },
lte: { type: TimeScalarType },
neq: { type: TimeScalarType },
is: { type: FilterIs },
},
});

View File

@ -1,14 +0,0 @@
import { GraphQLInputObjectType, GraphQLList } from 'graphql';
import { FilterIs } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/input/filter-is.input-type';
import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
export const UUIDFilterType = new GraphQLInputObjectType({
name: 'UUIDFilter',
fields: {
eq: { type: UUIDScalarType },
in: { type: new GraphQLList(UUIDScalarType) },
neq: { type: UUIDScalarType },
is: { type: FilterIs },
},
});

View File

@ -1,4 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { GraphQLSchema } from 'graphql';
@ -14,8 +14,6 @@ import { OrphanedTypesFactory } from './factories/orphaned-types.factory';
@Injectable()
export class WorkspaceGraphQLSchemaFactory {
private readonly logger = new Logger(WorkspaceGraphQLSchemaFactory.name);
constructor(
private readonly typeDefinitionsGenerator: TypeDefinitionsGenerator,
private readonly queryTypeFactory: QueryTypeFactory,

View File

@ -96,7 +96,7 @@ export class AISQLQueryService {
}
private getCreateTableStatement(tableName: string, colInfos: any[]) {
return `${`CREATE TABLE ${tableName} (\n`} ${colInfos
return `CREATE TABLE ${tableName} (\n ${colInfos
.map(
(colInfo) =>
`${colInfo.column_name} ${colInfo.data_type} ${

View File

@ -7,7 +7,7 @@ import { v4 as uuidv4 } from 'uuid';
import { AppToken } from 'src/engine/core-modules/app-token/app-token.entity';
export class BeforeCreateOneAppToken<T extends AppToken>
implements BeforeCreateOneHook<T, any>
implements BeforeCreateOneHook<T>
{
async run(
instance: CreateOneInputType<T>,

View File

@ -10,6 +10,7 @@ export class AuthException extends CustomException {
export enum AuthExceptionCode {
USER_NOT_FOUND = 'USER_NOT_FOUND',
CLIENT_NOT_FOUND = 'CLIENT_NOT_FOUND',
WORKSPACE_NOT_FOUND = 'WORKSPACE_NOT_FOUND',
INVALID_INPUT = 'INVALID_INPUT',
FORBIDDEN_EXCEPTION = 'FORBIDDEN_EXCEPTION',
UNAUTHENTICATED = 'UNAUTHENTICATED',

View File

@ -72,7 +72,7 @@ export class GoogleAPIsAuthController {
if (!workspaceId) {
throw new AuthException(
'Workspace not found',
AuthExceptionCode.INVALID_INPUT,
AuthExceptionCode.WORKSPACE_NOT_FOUND,
);
}

View File

@ -16,7 +16,6 @@ import {
export class AuthGraphqlApiExceptionFilter implements ExceptionFilter {
catch(exception: AuthException) {
switch (exception.code) {
case AuthExceptionCode.USER_NOT_FOUND:
case AuthExceptionCode.CLIENT_NOT_FOUND:
throw new NotFoundError(exception.message);
case AuthExceptionCode.INVALID_INPUT:
@ -24,6 +23,8 @@ export class AuthGraphqlApiExceptionFilter implements ExceptionFilter {
case AuthExceptionCode.FORBIDDEN_EXCEPTION:
throw new ForbiddenError(exception.message);
case AuthExceptionCode.UNAUTHENTICATED:
case AuthExceptionCode.USER_NOT_FOUND:
case AuthExceptionCode.WORKSPACE_NOT_FOUND:
throw new AuthenticationError(exception.message);
case AuthExceptionCode.INVALID_DATA:
case AuthExceptionCode.INTERNAL_SERVER_ERROR:

View File

@ -41,12 +41,6 @@ import { EnvironmentService } from 'src/engine/integrations/environment/environm
import { TokenService } from './token.service';
export type UserPayload = {
firstName: string;
lastName: string;
email: string;
};
@Injectable()
export class AuthService {
constructor(

View File

@ -52,7 +52,7 @@ export class JwtAuthStrategy extends PassportStrategy(Strategy, 'jwt') {
if (!workspace) {
throw new AuthException(
'Workspace not found',
AuthExceptionCode.INVALID_INPUT,
AuthExceptionCode.WORKSPACE_NOT_FOUND,
);
}

View File

@ -38,7 +38,7 @@ export class FileService {
const expirationDate = addMilliseconds(new Date(), ms(fileTokenExpiresIn));
const signedPayload = await this.jwtWrapperService.sign(
const signedPayload = this.jwtWrapperService.sign(
{
expiration_date: expirationDate,
...payloadToEncode,

View File

@ -115,12 +115,6 @@ export class WorkspaceService extends TypeOrmQueryService<Workspace> {
return workspace;
}
async getWorkspaceIds() {
return this.workspaceRepository
.find()
.then((workspaces) => workspaces.map((workspace) => workspace.id));
}
async handleRemoveWorkspaceMember(workspaceId: string, userId: string) {
await this.userWorkspaceRepository.delete({
userId,

View File

@ -1,11 +0,0 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { getRequest } from 'src/utils/extract-request';
export const UserAbility = createParamDecorator(
(_: unknown, context: ExecutionContext) => {
const request = getRequest(context);
return request.ability;
},
);

View File

@ -3,9 +3,6 @@ import { Logger } from '@nestjs/common';
/**
* A decorator function that logs the execution time of the decorated method.
*
* @param target The target class of the decorated method.
* @param propertyKey The name of the decorated method.
* @param descriptor The property descriptor of the decorated method.
* @returns The modified property descriptor with the execution time logging functionality.
*/
export function LogExecutionTime() {

View File

@ -1,8 +1,4 @@
import {
ConfigurableModuleBuilder,
FactoryProvider,
ModuleMetadata,
} from '@nestjs/common';
import { ConfigurableModuleBuilder } from '@nestjs/common';
import { ExceptionHandlerModuleOptions } from './interfaces';
@ -16,10 +12,3 @@ export const {
})
.setClassMethodName('forRoot')
.build();
export type ExceptionHandlerModuleAsyncOptions = {
useFactory: (
...args: any[]
) => ExceptionHandlerModuleOptions | Promise<ExceptionHandlerModuleOptions>;
} & Pick<ModuleMetadata, 'imports'> &
Pick<FactoryProvider, 'inject'>;

View File

@ -6,8 +6,9 @@ import { ExceptionHandlerDriver } from 'src/engine/integrations/exception-handle
/**
* ExceptionHandler Module factory
* @param environment
* @returns ExceptionHandlerModuleOptions
* @param environmentService
* @param adapterHost
*/
export const exceptionHandlerModuleFactory = async (
environmentService: EnvironmentService,

View File

@ -9,8 +9,8 @@ import { resolveAbsolutePath } from 'src/utils/resolve-absolute-path';
/**
* FileStorage Module factory
* @param environment
* @returns FileStorageModuleOptions
* @param environmentService
*/
export const fileStorageModuleFactory = async (
environmentService: EnvironmentService,

View File

@ -1,8 +1,4 @@
import {
ConfigurableModuleBuilder,
FactoryProvider,
ModuleMetadata,
} from '@nestjs/common';
import { ConfigurableModuleBuilder } from '@nestjs/common';
import { LoggerModuleOptions } from './interfaces';
@ -16,10 +12,3 @@ export const {
})
.setClassMethodName('forRoot')
.build();
export type LoggerModuleAsyncOptions = {
useFactory: (
...args: any[]
) => LoggerModuleOptions | Promise<LoggerModuleOptions>;
} & Pick<ModuleMetadata, 'imports'> &
Pick<FactoryProvider, 'inject'>;

View File

@ -6,8 +6,8 @@ import {
/**
* Logger Module factory
* @param environment
* @returns LoggerModuleOptions
* @param environmentService
*/
export const loggerModuleFactory = async (
environmentService: EnvironmentService,

View File

@ -12,7 +12,7 @@ import { MessageQueueDriver } from './interfaces/message-queue-driver.interface'
export class SyncDriver implements MessageQueueDriver {
private readonly logger = new Logger(SyncDriver.name);
private workersMap: {
[queueName: string]: (job: MessageQueueJob<any>) => Promise<void> | void;
[queueName: string]: (job: MessageQueueJob) => Promise<void> | void;
} = {};
constructor() {}

View File

@ -2,21 +2,18 @@
import { Injectable, Type } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { MessageQueueWorkerOptions } from 'src/engine/integrations/message-queue/interfaces/message-queue-worker-options.interface';
import { MessageQueueProcessOptions } from 'src/engine/integrations/message-queue/decorators/process.decorator';
import { MessageQueueProcessorOptions } from 'src/engine/integrations/message-queue/decorators/processor.decorator';
import {
PROCESSOR_METADATA,
PROCESS_METADATA,
WORKER_METADATA,
} from 'src/engine/integrations/message-queue/message-queue.constants';
@Injectable()
export class MessageQueueMetadataAccessor {
constructor(private readonly reflector: Reflector) {}
isProcessor(target: Type<any> | Function): boolean {
isProcessor(target: Type | Function): boolean {
if (!target) {
return false;
}
@ -24,7 +21,7 @@ export class MessageQueueMetadataAccessor {
return !!this.reflector.get(PROCESSOR_METADATA, target);
}
isProcess(target: Type<any> | Function): boolean {
isProcess(target: Type | Function): boolean {
if (!target) {
return false;
}
@ -33,22 +30,16 @@ export class MessageQueueMetadataAccessor {
}
getProcessorMetadata(
target: Type<any> | Function,
target: Type | Function,
): MessageQueueProcessorOptions | undefined {
return this.reflector.get(PROCESSOR_METADATA, target);
}
getProcessMetadata(
target: Type<any> | Function,
target: Type | Function,
): MessageQueueProcessOptions | undefined {
const metadata = this.reflector.get(PROCESS_METADATA, target);
return metadata;
}
getWorkerOptionsMetadata(
target: Type<any> | Function,
): MessageQueueWorkerOptions {
return this.reflector.get(WORKER_METADATA, target) ?? {};
}
}

View File

@ -6,8 +6,8 @@ import {
/**
* MessageQueue Module factory
* @param environment
* @returns MessageQueueModuleOptions
* @param environmentService
*/
export const messageQueueModuleFactory = async (
environmentService: EnvironmentService,

View File

@ -1,5 +0,0 @@
export function getJobClassName(name: string): string {
const [, jobName] = name.split('.') ?? [];
return jobName ?? name;
}

View File

@ -1,5 +1,4 @@
import { CompositeType } from 'src/engine/metadata-modules/field-metadata/interfaces/composite-type.interface';
import { FieldMetadataInterface } from 'src/engine/metadata-modules/field-metadata/interfaces/field-metadata.interface';
import { actorCompositeType } from 'src/engine/metadata-modules/field-metadata/composite-types/actor.composite-type';
import { addressCompositeType } from 'src/engine/metadata-modules/field-metadata/composite-types/address.composite-type';
@ -10,10 +9,6 @@ import { linkCompositeType } from 'src/engine/metadata-modules/field-metadata/co
import { linksCompositeType } from 'src/engine/metadata-modules/field-metadata/composite-types/links.composite-type';
import { FieldMetadataType } from 'src/engine/metadata-modules/field-metadata/field-metadata.entity';
export type CompositeFieldsDefinitionFunction = (
fieldMetadata?: FieldMetadataInterface,
) => FieldMetadataInterface[];
export const compositeTypeDefinitions = new Map<
FieldMetadataType,
CompositeType

View File

@ -94,7 +94,7 @@ export class FieldMetadataService extends TypeOrmQueryService<FieldMetadataEntit
try {
const fieldMetadataRepository =
queryRunner.manager.getRepository<FieldMetadataEntity<'default'>>(
queryRunner.manager.getRepository<FieldMetadataEntity>(
FieldMetadataEntity,
);
const objectMetadata =
@ -304,7 +304,7 @@ export class FieldMetadataService extends TypeOrmQueryService<FieldMetadataEntit
try {
const fieldMetadataRepository =
queryRunner.manager.getRepository<FieldMetadataEntity<'default'>>(
queryRunner.manager.getRepository<FieldMetadataEntity>(
FieldMetadataEntity,
);
@ -471,7 +471,7 @@ export class FieldMetadataService extends TypeOrmQueryService<FieldMetadataEntit
try {
const fieldMetadataRepository =
queryRunner.manager.getRepository<FieldMetadataEntity<'default'>>(
queryRunner.manager.getRepository<FieldMetadataEntity>(
FieldMetadataEntity,
);
@ -614,13 +614,6 @@ export class FieldMetadataService extends TypeOrmQueryService<FieldMetadataEntit
});
}
public async deleteFieldsMetadata(workspaceId: string) {
await this.fieldMetadataRepository.delete({ workspaceId });
await this.workspaceMetadataVersionService.incrementMetadataVersion(
workspaceId,
);
}
private buildUpdatableStandardFieldInput(
fieldMetadataInput: UpdateFieldInput,
existingFieldMetadata: FieldMetadataEntity,

View File

@ -52,12 +52,4 @@ export class IsFieldMetadataOptions {
return false;
}
}
defaultMessage(): string {
if (this.validationErrors.length > 0) {
return this.validationErrors.join(', ');
}
return 'FieldMetadataOptions is not valid';
}
}

View File

@ -9,7 +9,7 @@ import { CreateObjectInput } from 'src/engine/metadata-modules/object-metadata/d
@Injectable()
export class BeforeCreateOneObject<T extends CreateObjectInput>
implements BeforeCreateOneHook<T, any>
implements BeforeCreateOneHook<T>
{
async run(
instance: CreateOneInputType<T>,

View File

@ -12,7 +12,7 @@ import {
import { ObjectMetadataService } from 'src/engine/metadata-modules/object-metadata/object-metadata.service';
@Injectable()
export class BeforeDeleteOneObject implements BeforeDeleteOneHook<any> {
export class BeforeDeleteOneObject implements BeforeDeleteOneHook {
constructor(readonly objectMetadataService: ObjectMetadataService) {}
async run(

View File

@ -18,7 +18,7 @@ import { ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadat
@Injectable()
export class BeforeUpdateOneObject<T extends UpdateObjectPayload>
implements BeforeUpdateOneHook<T, any>
implements BeforeUpdateOneHook<T>
{
constructor(
readonly objectMetadataService: ObjectMetadataService,

View File

@ -399,31 +399,6 @@ export class ObjectMetadataService extends TypeOrmQueryService<ObjectMetadataEnt
});
}
public async findOneOrFailWithinWorkspace(
workspaceId: string,
options: FindOneOptions<ObjectMetadataEntity>,
): Promise<ObjectMetadataEntity> {
try {
return this.objectMetadataRepository.findOneOrFail({
relations: [
'fields',
'fields.fromRelationMetadata',
'fields.toRelationMetadata',
],
...options,
where: {
...options.where,
workspaceId,
},
});
} catch (error) {
throw new ObjectMetadataException(
'Object does not exist',
ObjectMetadataExceptionCode.OBJECT_METADATA_NOT_FOUND,
);
}
}
public async findManyWithinWorkspace(
workspaceId: string,
options?: FindManyOptions<ObjectMetadataEntity>,

View File

@ -9,7 +9,7 @@ import { CreateRelationInput } from 'src/engine/metadata-modules/relation-metada
@Injectable()
export class BeforeCreateOneRelation<T extends CreateRelationInput>
implements BeforeCreateOneHook<T, any>
implements BeforeCreateOneHook<T>
{
async run(
instance: CreateOneInputType<T>,

View File

@ -12,7 +12,7 @@ import {
import { RelationMetadataService } from 'src/engine/metadata-modules/relation-metadata/relation-metadata.service';
@Injectable()
export class BeforeDeleteOneRelation implements BeforeDeleteOneHook<any> {
export class BeforeDeleteOneRelation implements BeforeDeleteOneHook {
constructor(readonly relationMetadataService: RelationMetadataService) {}
async run(

View File

@ -601,7 +601,7 @@ export class RemoteTableService {
columnName: string,
columnType: string,
objectMetadataId: string,
): Promise<FieldMetadataEntity<'default'>> {
): Promise<FieldMetadataEntity> {
return this.fieldMetadataService.createOne({
name: columnName,
label: camelToTitleCase(columnName),

View File

@ -1,4 +1,4 @@
import { ArgsType, Field, InputType } from '@nestjs/graphql';
import { Field, InputType } from '@nestjs/graphql';
import { IsNotEmpty, IsObject, IsOptional, IsUUID } from 'class-validator';
import graphqlTypeJson from 'graphql-type-json';

View File

@ -14,7 +14,6 @@ import {
IsDateString,
IsEnum,
IsNotEmpty,
IsNumber,
IsString,
IsUUID,
} from 'class-validator';

View File

@ -3,7 +3,6 @@ import {
CreateDateColumn,
Entity,
PrimaryGeneratedColumn,
Unique,
UpdateDateColumn,
} from 'typeorm';

View File

@ -18,8 +18,8 @@ export class WorkspaceMigrationService {
/**
* Get all pending migrations for a given workspaceId
*
* @param workspaceId: string
* @returns Promise<WorkspaceMigration[]>
* @param workspaceId
*/
public async getPendingMigrations(
workspaceId: string,
@ -53,8 +53,8 @@ export class WorkspaceMigrationService {
* Set appliedAt as current date for a given migration.
* Should be called once the migration has been applied
*
* @param workspaceId: string
* @param migration: WorkspaceMigration
* @param workspaceId
* @param migration
*/
public async setAppliedAtForMigration(
workspaceId: string,
@ -69,6 +69,7 @@ export class WorkspaceMigrationService {
/**
* Create a new pending migration for a given workspaceId and expected changes
*
* @param name
* @param workspaceId
* @param migrations
*/

View File

@ -36,8 +36,4 @@ export class WorkspaceDataSource extends DataSource {
): WorkspaceEntityManager {
return new WorkspaceEntityManager(this.internalContext, this, queryRunner);
}
getWorkspaceId(): string {
return this.internalContext.workspaceId;
}
}

View File

@ -57,9 +57,7 @@ export function WorkspaceField<T extends FieldMetadataType>(
) ?? false;
const defaultValue = (options.defaultValue ??
generateDefaultValue(
options.type,
)) as FieldMetadataDefaultValue<'default'> | null;
generateDefaultValue(options.type)) as FieldMetadataDefaultValue | null;
metadataArgsStorage.addFields({
target: object.constructor,

View File

@ -3,10 +3,6 @@ import { metadataArgsStorage } from 'src/engine/twenty-orm/storage/metadata-args
import { convertClassNameToObjectMetadataName } from 'src/engine/workspace-manager/workspace-sync-metadata/utils/convert-class-to-object-metadata-name.util';
import { TypedReflect } from 'src/utils/typed-reflect';
export interface WorkspaceIndexOptions {
columns?: string[];
}
export function WorkspaceIndex(): PropertyDecorator;
export function WorkspaceIndex(columns: string[]): ClassDecorator;
export function WorkspaceIndex(

View File

@ -68,10 +68,6 @@ export class MetadataArgsStorage {
target: Function | string,
): WorkspaceExtendedEntityMetadataArgs | undefined;
filterExtendedEntities(
target: (Function | string)[],
): WorkspaceExtendedEntityMetadataArgs[];
filterExtendedEntities(
target: (Function | string) | (Function | string)[],
):
@ -85,8 +81,6 @@ export class MetadataArgsStorage {
filterFields(target: Function | string): WorkspaceFieldMetadataArgs[];
filterFields(target: (Function | string)[]): WorkspaceFieldMetadataArgs[];
filterFields(
target: (Function | string) | (Function | string)[],
): WorkspaceFieldMetadataArgs[] {
@ -107,8 +101,6 @@ export class MetadataArgsStorage {
filterIndexes(target: Function | string): WorkspaceIndexMetadataArgs[];
filterIndexes(target: (Function | string)[]): WorkspaceIndexMetadataArgs[];
filterIndexes(
target: (Function | string) | (Function | string)[],
): WorkspaceIndexMetadataArgs[] {
@ -119,10 +111,6 @@ export class MetadataArgsStorage {
target: Function | string,
): WorkspaceDynamicRelationMetadataArgs[];
filterDynamicRelations(
target: (Function | string)[],
): WorkspaceDynamicRelationMetadataArgs[];
filterDynamicRelations(
target: (Function | string) | (Function | string)[],
): WorkspaceDynamicRelationMetadataArgs[] {
@ -133,10 +121,6 @@ export class MetadataArgsStorage {
target: Function | string,
): WorkspaceJoinColumnsMetadataArgs[];
filterJoinColumns(
target: (Function | string)[],
): WorkspaceJoinColumnsMetadataArgs[];
filterJoinColumns(
target: (Function | string) | (Function | string)[],
): WorkspaceJoinColumnsMetadataArgs[] {

View File

@ -6,15 +6,6 @@ export class WorkspaceEntitiesStorage {
Map<string, EntitySchema>
>();
static getEntitySchema(
workspaceId: string,
objectMetadataName: string,
): EntitySchema | undefined {
const workspace = this.workspaceEntities.get(workspaceId);
return workspace?.get(objectMetadataName);
}
static setEntitySchema(
workspaceId: string,
objectMetadataName: string,
@ -38,12 +29,4 @@ export class WorkspaceEntitiesStorage {
([, schema]) => schema.options.name === target.options.name,
)?.[0];
}
static getEntities(workspaceId: string): EntitySchema[] {
return Array.from(this.workspaceEntities.get(workspaceId)?.values() || []);
}
static clearWorkspace(workspaceId: string): void {
this.workspaceEntities.delete(workspaceId);
}
}

View File

@ -1,4 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { EntitySchemaOptions } from 'typeorm';
@ -18,8 +18,6 @@ enum WorkspaceCacheKeys {
@Injectable()
export class WorkspaceCacheStorageService {
private readonly logger = new Logger(WorkspaceCacheStorageService.name);
constructor(
@InjectCacheStorage(CacheStorageNamespace.EngineWorkspace)
private readonly cacheStorageService: CacheStorageService,

View File

@ -20,7 +20,7 @@ export abstract class AbstractWorkspaceFixer<
> {
private issueTypes: IssueTypes[];
constructor(...issueTypes: IssueTypes[]) {
protected constructor(...issueTypes: IssueTypes[]) {
this.issueTypes = issueTypes;
}

View File

@ -112,13 +112,12 @@ export class WorkspaceDefaultValueFixer extends AbstractWorkspaceFixer<Workspace
for (const issue of issues) {
const currentDefaultValue:
| FieldMetadataDefaultValue<'default'>
| FieldMetadataDefaultValue
// Old format for default values
// TODO: Remove this after all workspaces are migrated
| { type: FieldMetadataDefaultValueFunctionNames }
| null = issue.fieldMetadata.defaultValue;
let alteredDefaultValue: FieldMetadataDefaultValue<'default'> | null =
null;
let alteredDefaultValue: FieldMetadataDefaultValue | null = null;
// Check if it's an old function default value
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
@ -189,7 +188,7 @@ export class WorkspaceDefaultValueFixer extends AbstractWorkspaceFixer<Workspace
private computeFieldMetadataDefaultValueFromColumnDefault(
columnDefault: string | undefined,
): FieldMetadataDefaultValue<'default'> {
): FieldMetadataDefaultValue {
if (
columnDefault === undefined ||
columnDefault === null ||

View File

@ -151,24 +151,6 @@ export class DatabaseStructureService {
}));
}
async workspaceColumnExist(
schemaName: string,
tableName: string,
columnName: string,
): Promise<boolean> {
const mainDataSource = this.typeORMService.getMainDataSource();
const results = await mainDataSource.query(
`SELECT column_name
FROM information_schema.columns
WHERE table_schema = $1
AND table_name = $2
AND column_name = $3`,
[schemaName, tableName, columnName],
);
return results.length >= 1;
}
getPostgresDataTypes(fieldMetadata: FieldMetadataEntity): string[] {
const mainDataSource = this.typeORMService.getMainDataSource();

View File

@ -76,22 +76,6 @@ export class WorkspaceManagerService {
await this.prefillWorkspaceWithDemoObjects(dataSourceMetadata, workspaceId);
}
/**
*
* Check if the workspace schema has already been created or not
*
* @param workspaceId
* @Returns Promise<boolean>
*/
public async doesDataSourceExist(workspaceId: string): Promise<boolean> {
const dataSource =
await this.dataSourceService.getDataSourcesMetadataFromWorkspaceId(
workspaceId,
);
return dataSource.length > 0;
}
/**
*
* We are updating the pg_graphql max_rows from 30 (default value) to 60

View File

@ -1,4 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import {
QueryRunner,
@ -32,8 +32,6 @@ import { customTableDefaultColumns } from './utils/custom-table-default-column.u
@Injectable()
export class WorkspaceMigrationRunnerService {
private readonly logger = new Logger(WorkspaceMigrationRunnerService.name);
constructor(
private readonly workspaceDataSourceService: WorkspaceDataSourceService,
private readonly workspaceMigrationService: WorkspaceMigrationService,

View File

@ -1,19 +0,0 @@
import { PartialFieldMetadata } from 'src/engine/workspace-manager/workspace-sync-metadata/interfaces/partial-field-metadata.interface';
import { PartialWorkspaceEntity } from 'src/engine/workspace-manager/workspace-sync-metadata/interfaces/partial-object-metadata.interface';
import { ObjectMetadataEntity } from 'src/engine/metadata-modules/object-metadata/object-metadata.entity';
import { FieldMetadataEntity } from 'src/engine/metadata-modules/field-metadata/field-metadata.entity';
export type MappedFieldMetadata = Record<string, PartialFieldMetadata>;
export interface MappedWorkspaceEntity
extends Omit<PartialWorkspaceEntity, 'fields'> {
fields: MappedFieldMetadata;
}
export type MappedFieldMetadataEntity = Record<string, FieldMetadataEntity>;
export interface MappedObjectMetadataEntity
extends Omit<ObjectMetadataEntity, 'fields'> {
fields: MappedFieldMetadataEntity;
}

View File

@ -1,4 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import {
EntityManager,
@ -27,8 +27,6 @@ import { WorkspaceSyncStorage } from 'src/engine/workspace-manager/workspace-syn
@Injectable()
export class WorkspaceMetadataUpdaterService {
private readonly logger = new Logger(WorkspaceMetadataUpdaterService.name);
async updateObjectMetadata(
manager: EntityManager,
storage: WorkspaceSyncStorage,
@ -127,12 +125,13 @@ export class WorkspaceMetadataUpdaterService {
/**
* Update field metadata
*/
const updatedFieldMetadataCollection = await this.updateEntities<
FieldMetadataEntity<'default'>
>(manager, FieldMetadataEntity, storage.fieldMetadataUpdateCollection, [
'objectMetadataId',
'workspaceId',
]);
const updatedFieldMetadataCollection =
await this.updateEntities<FieldMetadataEntity>(
manager,
FieldMetadataEntity,
storage.fieldMetadataUpdateCollection,
['objectMetadataId', 'workspaceId'],
);
/**
* Create field metadata

View File

@ -1,4 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { EntityManager, Repository } from 'typeorm';
@ -17,10 +17,6 @@ import { mapObjectMetadataByUniqueIdentifier } from 'src/engine/workspace-manage
@Injectable()
export class WorkspaceSyncObjectMetadataIdentifiersService {
private readonly logger = new Logger(
WorkspaceSyncObjectMetadataIdentifiersService.name,
);
constructor(private readonly standardObjectFactory: StandardObjectFactory) {}
async synchronize(

View File

@ -1,4 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { EntityManager } from 'typeorm';
@ -21,10 +21,6 @@ import { CustomWorkspaceEntity } from 'src/engine/twenty-orm/custom.workspace-en
@Injectable()
export class WorkspaceSyncRelationMetadataService {
private readonly logger = new Logger(
WorkspaceSyncRelationMetadataService.name,
);
constructor(
private readonly standardRelationFactory: StandardRelationFactory,
private readonly workspaceRelationComparator: WorkspaceRelationComparator,

View File

@ -84,10 +84,6 @@ export class WorkspaceSyncStorage {
return this._indexMetadataCreateCollection;
}
get indexMetadataUpdateCollection() {
return this._indexMetadataUpdateCollection;
}
get indexMetadataDeleteCollection() {
return this._indexMetadataDeleteCollection;
}
@ -138,10 +134,6 @@ export class WorkspaceSyncStorage {
this._indexMetadataCreateCollection.push(index);
}
addUpdateIndexMetadata(index: Partial<IndexMetadataEntity>) {
this._indexMetadataUpdateCollection.push(index);
}
addDeleteIndexMetadata(index: IndexMetadataEntity) {
this._indexMetadataDeleteCollection.push(index);
}

View File

@ -4,6 +4,7 @@
* Each object in the map contains the original object metadata and its fields as a nested map.
*
* @param arr - The array of ObjectMetadataEntity objects to convert.
* @param keyFactory
* @returns A map of object metadata, with nameSingular as the key and the object as the value.
*/
export const mapObjectMetadataByUniqueIdentifier = <

View File

@ -42,8 +42,8 @@ export class WorkspaceSyncMetadataService {
* Sync all standard objects and fields metadata for a given workspace and data source
* This will update the metadata if it has changed and generate migrations based on the diff.
*
* @param dataSourceId
* @param workspaceId
* @param context
* @param options
*/
public async synchronize(
context: WorkspaceSyncContext,

View File

@ -49,21 +49,4 @@ export class BlocklistRepository {
transactionManager,
);
}
public async getByWorkspaceMemberIdAndHandle(
workspaceMemberId: string,
handle: string,
workspaceId: string,
transactionManager?: EntityManager,
): Promise<BlocklistWorkspaceEntity[]> {
const dataSourceSchema =
this.workspaceDataSourceService.getSchemaName(workspaceId);
return await this.workspaceDataSourceService.executeRawQuery(
`SELECT * FROM ${dataSourceSchema}."blocklist" WHERE "workspaceMemberId" = $1 AND "handle" = $2`,
[workspaceMemberId, handle],
workspaceId,
transactionManager,
);
}
}

View File

@ -1 +0,0 @@
export const CALENDAR_THROTTLE_DURATION = 1000 * 60 * 1; // 1 minute

View File

@ -109,18 +109,6 @@ export class CalendarChannelSyncStatusService {
});
}
public async markAsCalendarEventsImportOngoing(calendarChannelId: string) {
const calendarChannelRepository =
await this.twentyORMManager.getRepository<CalendarChannelWorkspaceEntity>(
'calendarChannel',
);
await calendarChannelRepository.update(calendarChannelId, {
syncStage: CalendarChannelSyncStage.CALENDAR_EVENTS_IMPORT_ONGOING,
syncStatus: CalendarChannelSyncStatus.ONGOING,
});
}
public async markAsCompletedAndSchedulePartialMessageListFetch(
calendarChannelId: string,
) {

View File

@ -26,31 +26,3 @@ export const valuesStringForBatchRawQuery = (
return castedValues.join(', ');
};
export const getFlattenedValuesAndValuesStringForBatchRawQuery = (
values: {
[key: string]: any;
}[],
keyTypeMap: {
[key: string]: string;
},
): {
flattenedValues: any[];
valuesString: string;
} => {
const keysToInsert = Object.keys(keyTypeMap);
const flattenedValues = values.flatMap((value) =>
keysToInsert.map((key) => value[key]),
);
const valuesString = valuesStringForBatchRawQuery(
values,
Object.values(keyTypeMap),
);
return {
flattenedValues,
valuesString,
};
};

View File

@ -61,41 +61,6 @@ export class ConnectedAccountRepository {
return connectedAccounts;
}
public async getAllByUserId(
userId: string,
workspaceId: string,
transactionManager?: EntityManager,
): Promise<ConnectedAccountWorkspaceEntity[] | undefined> {
const schemaExists =
await this.workspaceDataSourceService.checkSchemaExists(workspaceId);
if (!schemaExists) {
return;
}
const dataSourceSchema =
this.workspaceDataSourceService.getSchemaName(workspaceId);
const workspaceMember = (
await this.workspaceDataSourceService.executeRawQuery(
`SELECT * FROM ${dataSourceSchema}."workspaceMember" WHERE "userId" = $1`,
[userId],
workspaceId,
transactionManager,
)
)?.[0];
if (!workspaceMember) {
return;
}
return await this.getAllByWorkspaceMemberId(
workspaceMember.id,
workspaceId,
transactionManager,
);
}
public async getAllByHandleAndWorkspaceMemberId(
handle: string,
workspaceMemberId: string,
@ -204,58 +169,6 @@ export class ConnectedAccountRepository {
return connectedAccount;
}
public async updateLastSyncHistoryId(
historyId: string,
connectedAccountId: string,
workspaceId: string,
transactionManager?: EntityManager,
) {
const dataSourceSchema =
this.workspaceDataSourceService.getSchemaName(workspaceId);
await this.workspaceDataSourceService.executeRawQuery(
`UPDATE ${dataSourceSchema}."connectedAccount" SET "lastSyncHistoryId" = $1 WHERE "id" = $2`,
[historyId, connectedAccountId],
workspaceId,
transactionManager,
);
}
public async updateLastSyncHistoryIdIfHigher(
historyId: string,
connectedAccountId: string,
workspaceId: string,
transactionManager?: EntityManager,
) {
const dataSourceSchema =
this.workspaceDataSourceService.getSchemaName(workspaceId);
await this.workspaceDataSourceService.executeRawQuery(
`UPDATE ${dataSourceSchema}."connectedAccount" SET "lastSyncHistoryId" = $1
WHERE "id" = $2
AND ("lastSyncHistoryId" < $1 OR "lastSyncHistoryId" = '')`,
[historyId, connectedAccountId],
workspaceId,
transactionManager,
);
}
public async deleteHistoryId(
connectedAccountId: string,
workspaceId: string,
transactionManager?: EntityManager,
) {
const dataSourceSchema =
this.workspaceDataSourceService.getSchemaName(workspaceId);
await this.workspaceDataSourceService.executeRawQuery(
`UPDATE ${dataSourceSchema}."connectedAccount" SET "lastSyncHistoryId" = '' WHERE "id" = $1`,
[connectedAccountId],
workspaceId,
transactionManager,
);
}
public async updateAccessToken(
accessToken: string,
connectedAccountId: string,