Upsert endpoint and CSV import upsert (#5970)
This PR introduces an `upsert` parameter (along the existing `data` param) for `createOne` and `createMany` mutations. When upsert is set to `true`, the function will look for records with the same id if an id was passed. If not id was passed, it will leverage the existing duplicate check mechanism to find a duplicate. If a record is found, then the function will perform an update instead of a create. Unfortunately I had to remove some nice tests that existing on the args factory. Those tests where mostly testing the duplication rule generation logic but through a GraphQL angle. Since I moved the duplication rule logic to a dedicated service, if I kept the tests but mocked the service we wouldn't really be testing anything useful. The right path would be to create new tests for this service that compare the JSON output and not the GraphQL output but I chose not to work on this as it's equivalent to rewriting the tests from scratch and I have other competing priorities.
This commit is contained in:
@ -1,206 +0,0 @@
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
|
||||
import { RecordFilter } from 'src/engine/api/graphql/workspace-query-builder/interfaces/record.interface';
|
||||
import { FindDuplicatesResolverArgs } from 'src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface';
|
||||
|
||||
import { ArgsAliasFactory } from 'src/engine/api/graphql/workspace-query-builder/factories/args-alias.factory';
|
||||
import { FieldsStringFactory } from 'src/engine/api/graphql/workspace-query-builder/factories/fields-string.factory';
|
||||
import { FindDuplicatesQueryFactory } from 'src/engine/api/graphql/workspace-query-builder/factories/find-duplicates-query.factory';
|
||||
import { workspaceQueryBuilderOptionsMock } from 'src/engine/api/graphql/workspace-query-builder/__mocks__/workspace-query-builder-options.mock';
|
||||
|
||||
describe('FindDuplicatesQueryFactory', () => {
|
||||
let service: FindDuplicatesQueryFactory;
|
||||
const argAliasCreate = jest.fn();
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.resetAllMocks();
|
||||
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
providers: [
|
||||
FindDuplicatesQueryFactory,
|
||||
{
|
||||
provide: FieldsStringFactory,
|
||||
useValue: {
|
||||
create: jest.fn().mockResolvedValue('fieldsString'),
|
||||
// Mock implementation of FieldsStringFactory methods if needed
|
||||
},
|
||||
},
|
||||
{
|
||||
provide: ArgsAliasFactory,
|
||||
useValue: {
|
||||
create: argAliasCreate,
|
||||
// Mock implementation of ArgsAliasFactory methods if needed
|
||||
},
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
|
||||
service = module.get<FindDuplicatesQueryFactory>(
|
||||
FindDuplicatesQueryFactory,
|
||||
);
|
||||
});
|
||||
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('should return (first: 0) as a filter when args are missing', async () => {
|
||||
const args: FindDuplicatesResolverArgs<RecordFilter> = {};
|
||||
|
||||
const query = await service.create(
|
||||
args,
|
||||
workspaceQueryBuilderOptionsMock,
|
||||
);
|
||||
|
||||
expect(query.trim()).toEqual(`query {
|
||||
objectNameCollection(first: 0) {
|
||||
fieldsString
|
||||
}
|
||||
}`);
|
||||
});
|
||||
|
||||
it('should use firstName and lastName as a filter when both args are present', async () => {
|
||||
argAliasCreate.mockReturnValue({
|
||||
nameFirstName: 'John',
|
||||
nameLastName: 'Doe',
|
||||
});
|
||||
|
||||
const args: FindDuplicatesResolverArgs<RecordFilter> = {
|
||||
data: {
|
||||
name: {
|
||||
firstName: 'John',
|
||||
lastName: 'Doe',
|
||||
},
|
||||
} as unknown as RecordFilter,
|
||||
};
|
||||
|
||||
const query = await service.create(args, {
|
||||
...workspaceQueryBuilderOptionsMock,
|
||||
objectMetadataItem: {
|
||||
...workspaceQueryBuilderOptionsMock.objectMetadataItem,
|
||||
nameSingular: 'person',
|
||||
},
|
||||
});
|
||||
|
||||
expect(query.trim()).toEqual(`query {
|
||||
personCollection(filter: {or:[{nameFirstName:{eq:"John"},nameLastName:{eq:"Doe"}}]}) {
|
||||
fieldsString
|
||||
}
|
||||
}`);
|
||||
});
|
||||
|
||||
it('should ignore an argument if the string length is less than 3', async () => {
|
||||
argAliasCreate.mockReturnValue({
|
||||
linkedinLinkUrl: 'ab',
|
||||
email: 'test@test.com',
|
||||
});
|
||||
|
||||
const args: FindDuplicatesResolverArgs<RecordFilter> = {
|
||||
data: {
|
||||
linkedinLinkUrl: 'ab',
|
||||
email: 'test@test.com',
|
||||
} as unknown as RecordFilter,
|
||||
};
|
||||
|
||||
const query = await service.create(args, {
|
||||
...workspaceQueryBuilderOptionsMock,
|
||||
objectMetadataItem: {
|
||||
...workspaceQueryBuilderOptionsMock.objectMetadataItem,
|
||||
nameSingular: 'person',
|
||||
},
|
||||
});
|
||||
|
||||
expect(query.trim()).toEqual(`query {
|
||||
personCollection(filter: {or:[{email:{eq:"test@test.com"}}]}) {
|
||||
fieldsString
|
||||
}
|
||||
}`);
|
||||
});
|
||||
|
||||
it('should return (first: 0) as a filter when only firstName is present', async () => {
|
||||
argAliasCreate.mockReturnValue({
|
||||
nameFirstName: 'John',
|
||||
});
|
||||
|
||||
const args: FindDuplicatesResolverArgs<RecordFilter> = {
|
||||
data: {
|
||||
name: {
|
||||
firstName: 'John',
|
||||
},
|
||||
} as unknown as RecordFilter,
|
||||
};
|
||||
|
||||
const query = await service.create(args, {
|
||||
...workspaceQueryBuilderOptionsMock,
|
||||
objectMetadataItem: {
|
||||
...workspaceQueryBuilderOptionsMock.objectMetadataItem,
|
||||
nameSingular: 'person',
|
||||
},
|
||||
});
|
||||
|
||||
expect(query.trim()).toEqual(`query {
|
||||
personCollection(first: 0) {
|
||||
fieldsString
|
||||
}
|
||||
}`);
|
||||
});
|
||||
|
||||
it('should use "currentRecord" as query args when its present', async () => {
|
||||
argAliasCreate.mockReturnValue({
|
||||
nameFirstName: 'John',
|
||||
});
|
||||
|
||||
const args: FindDuplicatesResolverArgs<RecordFilter> = {
|
||||
id: 'uuid',
|
||||
};
|
||||
|
||||
const query = await service.create(
|
||||
args,
|
||||
{
|
||||
...workspaceQueryBuilderOptionsMock,
|
||||
objectMetadataItem: {
|
||||
...workspaceQueryBuilderOptionsMock.objectMetadataItem,
|
||||
nameSingular: 'person',
|
||||
},
|
||||
},
|
||||
{
|
||||
nameFirstName: 'Peter',
|
||||
nameLastName: 'Parker',
|
||||
},
|
||||
);
|
||||
|
||||
expect(query.trim()).toEqual(`query {
|
||||
personCollection(filter: {id:{neq:"uuid"},or:[{nameFirstName:{eq:"Peter"},nameLastName:{eq:"Parker"}}]}) {
|
||||
fieldsString
|
||||
}
|
||||
}`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildQueryForExistingRecord', () => {
|
||||
it(`should include all the fields that exist for person inside "duplicateCriteriaCollection" constant`, async () => {
|
||||
const query = service.buildQueryForExistingRecord('uuid', {
|
||||
...workspaceQueryBuilderOptionsMock,
|
||||
objectMetadataItem: {
|
||||
...workspaceQueryBuilderOptionsMock.objectMetadataItem,
|
||||
nameSingular: 'person',
|
||||
},
|
||||
});
|
||||
|
||||
expect(query.trim()).toEqual(`query {
|
||||
personCollection(filter: { id: { eq: "uuid" }}){
|
||||
edges {
|
||||
node {
|
||||
__typename
|
||||
nameFirstName
|
||||
nameLastName
|
||||
linkedinLinkUrl
|
||||
email
|
||||
}
|
||||
}
|
||||
}
|
||||
}`);
|
||||
});
|
||||
});
|
||||
});
|
||||
@ -22,7 +22,7 @@ export class CreateManyQueryFactory {
|
||||
) {}
|
||||
|
||||
async create<Record extends IRecord = IRecord>(
|
||||
args: CreateManyResolverArgs<Record>,
|
||||
args: CreateManyResolverArgs<Partial<Record>>,
|
||||
options: WorkspaceQueryBuilderOptions,
|
||||
) {
|
||||
const fieldsString = await this.fieldsStringFactory.create(
|
||||
|
||||
@ -6,6 +6,7 @@ import isEmpty from 'lodash.isempty';
|
||||
|
||||
import { FieldMetadataInterface } from 'src/engine/metadata-modules/field-metadata/interfaces/field-metadata.interface';
|
||||
import { ObjectMetadataInterface } from 'src/engine/metadata-modules/field-metadata/interfaces/object-metadata.interface';
|
||||
import { Record } from 'src/engine/api/graphql/workspace-query-builder/interfaces/record.interface';
|
||||
|
||||
import { isRelationFieldMetadataType } from 'src/engine/utils/is-relation-field-metadata-type.util';
|
||||
|
||||
@ -26,7 +27,7 @@ export class FieldsStringFactory {
|
||||
fieldMetadataCollection: FieldMetadataInterface[],
|
||||
objectMetadataCollection: ObjectMetadataInterface[],
|
||||
): Promise<string> {
|
||||
const selectedFields: Record<string, any> = graphqlFields(info);
|
||||
const selectedFields: Partial<Record> = graphqlFields(info);
|
||||
|
||||
return this.createFieldsStringRecursive(
|
||||
info,
|
||||
@ -38,7 +39,7 @@ export class FieldsStringFactory {
|
||||
|
||||
async createFieldsStringRecursive(
|
||||
info: GraphQLResolveInfo,
|
||||
selectedFields: Record<string, any>,
|
||||
selectedFields: Partial<Record>,
|
||||
fieldMetadataCollection: FieldMetadataInterface[],
|
||||
objectMetadataCollection: ObjectMetadataInterface[],
|
||||
accumulator = '',
|
||||
|
||||
@ -3,15 +3,13 @@ import { Injectable, Logger } from '@nestjs/common';
|
||||
import isEmpty from 'lodash.isempty';
|
||||
|
||||
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';
|
||||
import { Record } from 'src/engine/api/graphql/workspace-query-builder/interfaces/record.interface';
|
||||
import { FindDuplicatesResolverArgs } from 'src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface';
|
||||
import { ObjectMetadataInterface } from 'src/engine/metadata-modules/field-metadata/interfaces/object-metadata.interface';
|
||||
|
||||
import { computeObjectTargetTable } from 'src/engine/utils/compute-object-target-table.util';
|
||||
import { stringifyWithoutKeyQuote } from 'src/engine/api/graphql/workspace-query-builder/utils/stringify-without-key-quote.util';
|
||||
import { ArgsAliasFactory } from 'src/engine/api/graphql/workspace-query-builder/factories/args-alias.factory';
|
||||
import { DUPLICATE_CRITERIA_COLLECTION } from 'src/engine/api/graphql/workspace-resolver-builder/constants/duplicate-criteria.constants';
|
||||
import { settings } from 'src/engine/constants/settings';
|
||||
import { DuplicateService } from 'src/engine/core-modules/duplicate/duplicate.service';
|
||||
|
||||
import { FieldsStringFactory } from './fields-string.factory';
|
||||
|
||||
@ -22,12 +20,13 @@ export class FindDuplicatesQueryFactory {
|
||||
constructor(
|
||||
private readonly fieldsStringFactory: FieldsStringFactory,
|
||||
private readonly argsAliasFactory: ArgsAliasFactory,
|
||||
private readonly duplicateService: DuplicateService,
|
||||
) {}
|
||||
|
||||
async create<Filter extends RecordFilter = RecordFilter>(
|
||||
args: FindDuplicatesResolverArgs<Filter>,
|
||||
async create(
|
||||
args: FindDuplicatesResolverArgs,
|
||||
options: WorkspaceQueryBuilderOptions,
|
||||
currentRecord?: Record<string, unknown>,
|
||||
existingRecords?: Record[],
|
||||
) {
|
||||
const fieldsString = await this.fieldsStringFactory.create(
|
||||
options.info,
|
||||
@ -35,121 +34,66 @@ export class FindDuplicatesQueryFactory {
|
||||
options.objectMetadataCollection,
|
||||
);
|
||||
|
||||
const argsData = this.getFindDuplicateBy<Filter>(
|
||||
args,
|
||||
options,
|
||||
currentRecord,
|
||||
);
|
||||
if (existingRecords) {
|
||||
const query = existingRecords.reduce((acc, record, index) => {
|
||||
return (
|
||||
acc + this.buildQuery(fieldsString, options, undefined, record, index)
|
||||
);
|
||||
}, '');
|
||||
|
||||
const duplicateCondition = this.buildDuplicateCondition(
|
||||
options.objectMetadataItem,
|
||||
argsData,
|
||||
args.id,
|
||||
);
|
||||
return `query {
|
||||
${query}
|
||||
}`;
|
||||
}
|
||||
|
||||
const query = args.data?.reduce((acc, dataItem, index) => {
|
||||
const argsData = this.argsAliasFactory.create(
|
||||
dataItem ?? {},
|
||||
options.fieldMetadataCollection,
|
||||
);
|
||||
|
||||
return (
|
||||
acc +
|
||||
this.buildQuery(
|
||||
fieldsString,
|
||||
options,
|
||||
argsData as Record,
|
||||
undefined,
|
||||
index,
|
||||
)
|
||||
);
|
||||
}, '');
|
||||
|
||||
return `query {
|
||||
${query}
|
||||
}`;
|
||||
}
|
||||
|
||||
buildQuery(
|
||||
fieldsString: string,
|
||||
options: WorkspaceQueryBuilderOptions,
|
||||
data?: Record,
|
||||
existingRecord?: Record,
|
||||
index?: number,
|
||||
) {
|
||||
const duplicateCondition =
|
||||
this.duplicateService.buildDuplicateConditionForGraphQL(
|
||||
options.objectMetadataItem,
|
||||
data ?? existingRecord,
|
||||
existingRecord?.id,
|
||||
);
|
||||
|
||||
const filters = stringifyWithoutKeyQuote(duplicateCondition);
|
||||
|
||||
return `
|
||||
query {
|
||||
${computeObjectTargetTable(options.objectMetadataItem)}Collection${
|
||||
isEmpty(duplicateCondition?.or)
|
||||
? '(first: 0)'
|
||||
: `(filter: ${filters})`
|
||||
} {
|
||||
${fieldsString}
|
||||
}
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
getFindDuplicateBy<Filter extends RecordFilter = RecordFilter>(
|
||||
args: FindDuplicatesResolverArgs<Filter>,
|
||||
options: WorkspaceQueryBuilderOptions,
|
||||
currentRecord?: Record<string, unknown>,
|
||||
) {
|
||||
if (currentRecord) {
|
||||
return currentRecord;
|
||||
return `${computeObjectTargetTable(
|
||||
options.objectMetadataItem,
|
||||
)}Collection${index}: ${computeObjectTargetTable(
|
||||
options.objectMetadataItem,
|
||||
)}Collection${
|
||||
isEmpty(duplicateCondition?.or) ? '(first: 0)' : `(filter: ${filters})`
|
||||
} {
|
||||
${fieldsString}
|
||||
}
|
||||
|
||||
return this.argsAliasFactory.create(
|
||||
args.data ?? {},
|
||||
options.fieldMetadataCollection,
|
||||
);
|
||||
}
|
||||
|
||||
buildQueryForExistingRecord(
|
||||
id: string | number,
|
||||
options: WorkspaceQueryBuilderOptions,
|
||||
) {
|
||||
const idQueryField = typeof id === 'string' ? `"${id}"` : id;
|
||||
|
||||
return `
|
||||
query {
|
||||
${computeObjectTargetTable(
|
||||
options.objectMetadataItem,
|
||||
)}Collection(filter: { id: { eq: ${idQueryField} }}){
|
||||
edges {
|
||||
node {
|
||||
__typename
|
||||
${this.getApplicableDuplicateCriteriaCollection(
|
||||
options.objectMetadataItem,
|
||||
)
|
||||
.flatMap((dc) => dc.columnNames)
|
||||
.join('\n')}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
private buildDuplicateCondition(
|
||||
objectMetadataItem: ObjectMetadataInterface,
|
||||
argsData?: Record<string, unknown>,
|
||||
filteringByExistingRecordId?: string,
|
||||
) {
|
||||
if (!argsData) {
|
||||
return;
|
||||
}
|
||||
|
||||
const criteriaCollection =
|
||||
this.getApplicableDuplicateCriteriaCollection(objectMetadataItem);
|
||||
|
||||
const criteriaWithMatchingArgs = criteriaCollection.filter((criteria) =>
|
||||
criteria.columnNames.every((columnName) => {
|
||||
const value = argsData[columnName] as string | undefined;
|
||||
|
||||
return (
|
||||
!!value && value.length >= settings.minLengthOfStringForDuplicateCheck
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
const filterCriteria = criteriaWithMatchingArgs.map((criteria) =>
|
||||
Object.fromEntries(
|
||||
criteria.columnNames.map((columnName) => [
|
||||
columnName,
|
||||
{ eq: argsData[columnName] },
|
||||
]),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
// when filtering by an existing record, we need to filter that explicit record out
|
||||
...(filteringByExistingRecordId && {
|
||||
id: { neq: filteringByExistingRecordId },
|
||||
}),
|
||||
// keep condition as "or" to get results by more duplicate criteria
|
||||
or: filterCriteria,
|
||||
};
|
||||
}
|
||||
|
||||
private getApplicableDuplicateCriteriaCollection(
|
||||
objectMetadataItem: ObjectMetadataInterface,
|
||||
) {
|
||||
return DUPLICATE_CRITERIA_COLLECTION.filter(
|
||||
(duplicateCriteria) =>
|
||||
duplicateCriteria.objectName === objectMetadataItem.nameSingular,
|
||||
);
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
@ -28,7 +28,7 @@ export class UpdateManyQueryFactory {
|
||||
Record extends IRecord = IRecord,
|
||||
Filter extends RecordFilter = RecordFilter,
|
||||
>(
|
||||
args: UpdateManyResolverArgs<Record, Filter>,
|
||||
args: UpdateManyResolverArgs<Partial<Record>, Filter>,
|
||||
options: UpdateManyQueryFactoryOptions,
|
||||
) {
|
||||
const fieldsString = await this.fieldsStringFactory.create(
|
||||
|
||||
@ -20,7 +20,7 @@ export class UpdateOneQueryFactory {
|
||||
) {}
|
||||
|
||||
async create<Record extends IRecord = IRecord>(
|
||||
args: UpdateOneResolverArgs<Record>,
|
||||
args: UpdateOneResolverArgs<Partial<Record>>,
|
||||
options: WorkspaceQueryBuilderOptions,
|
||||
) {
|
||||
const fieldsString = await this.fieldsStringFactory.create(
|
||||
@ -35,6 +35,7 @@ export class UpdateOneQueryFactory {
|
||||
|
||||
const argsData = {
|
||||
...computedArgs.data,
|
||||
id: undefined, // do not allow updating an existing object's id
|
||||
updatedAt: new Date().toISOString(),
|
||||
};
|
||||
|
||||
|
||||
@ -64,37 +64,27 @@ export class WorkspaceQueryBuilderFactory {
|
||||
return this.findOneQueryFactory.create<Filter>(args, options);
|
||||
}
|
||||
|
||||
findDuplicates<Filter extends RecordFilter = RecordFilter>(
|
||||
args: FindDuplicatesResolverArgs<Filter>,
|
||||
findDuplicates(
|
||||
args: FindDuplicatesResolverArgs,
|
||||
options: WorkspaceQueryBuilderOptions,
|
||||
existingRecord?: Record<string, unknown>,
|
||||
existingRecords?: IRecord[],
|
||||
): Promise<string> {
|
||||
return this.findDuplicatesQueryFactory.create<Filter>(
|
||||
return this.findDuplicatesQueryFactory.create(
|
||||
args,
|
||||
options,
|
||||
existingRecord,
|
||||
);
|
||||
}
|
||||
|
||||
findDuplicatesExistingRecord(
|
||||
id: string | number,
|
||||
options: WorkspaceQueryBuilderOptions,
|
||||
): string {
|
||||
return this.findDuplicatesQueryFactory.buildQueryForExistingRecord(
|
||||
id,
|
||||
options,
|
||||
existingRecords,
|
||||
);
|
||||
}
|
||||
|
||||
createMany<Record extends IRecord = IRecord>(
|
||||
args: CreateManyResolverArgs<Record>,
|
||||
args: CreateManyResolverArgs<Partial<Record>>,
|
||||
options: WorkspaceQueryBuilderOptions,
|
||||
): Promise<string> {
|
||||
return this.createManyQueryFactory.create<Record>(args, options);
|
||||
}
|
||||
|
||||
updateOne<Record extends IRecord = IRecord>(
|
||||
initialArgs: UpdateOneResolverArgs<Record>,
|
||||
initialArgs: UpdateOneResolverArgs<Partial<Record>>,
|
||||
options: WorkspaceQueryBuilderOptions,
|
||||
): Promise<string> {
|
||||
return this.updateOneQueryFactory.create<Record>(initialArgs, options);
|
||||
@ -111,7 +101,7 @@ export class WorkspaceQueryBuilderFactory {
|
||||
Record extends IRecord = IRecord,
|
||||
Filter extends RecordFilter = RecordFilter,
|
||||
>(
|
||||
args: UpdateManyResolverArgs<Record, Filter>,
|
||||
args: UpdateManyResolverArgs<Partial<Record>, Filter>,
|
||||
options: UpdateManyQueryFactoryOptions,
|
||||
): Promise<string> {
|
||||
return this.updateManyQueryFactory.create(args, options);
|
||||
|
||||
@ -3,13 +3,14 @@ import { Module } from '@nestjs/common';
|
||||
import { ObjectMetadataModule } from 'src/engine/metadata-modules/object-metadata/object-metadata.module';
|
||||
import { FieldsStringFactory } from 'src/engine/api/graphql/workspace-query-builder/factories/fields-string.factory';
|
||||
import { RecordPositionQueryFactory } from 'src/engine/api/graphql/workspace-query-builder/factories/record-position-query.factory';
|
||||
import { DuplicateModule } from 'src/engine/core-modules/duplicate/duplicate.module';
|
||||
|
||||
import { WorkspaceQueryBuilderFactory } from './workspace-query-builder.factory';
|
||||
|
||||
import { workspaceQueryBuilderFactories } from './factories/factories';
|
||||
|
||||
@Module({
|
||||
imports: [ObjectMetadataModule],
|
||||
imports: [ObjectMetadataModule, DuplicateModule],
|
||||
providers: [...workspaceQueryBuilderFactories, WorkspaceQueryBuilderFactory],
|
||||
exports: [
|
||||
WorkspaceQueryBuilderFactory,
|
||||
|
||||
@ -152,8 +152,8 @@ describe('QueryRunnerArgsFactory', () => {
|
||||
} as WorkspaceQueryRunnerOptions;
|
||||
|
||||
const args = {
|
||||
id: '123',
|
||||
data: { testNumber: '1', otherField: 'test' },
|
||||
ids: ['123'],
|
||||
data: [{ testNumber: '1', otherField: 'test' }],
|
||||
};
|
||||
|
||||
const result = await factory.create(
|
||||
@ -163,8 +163,8 @@ describe('QueryRunnerArgsFactory', () => {
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
id: 123,
|
||||
data: { testNumber: 1, otherField: 'test' },
|
||||
ids: [123],
|
||||
data: [{ testNumber: 1, position: 2, otherField: 'test' }],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@ -10,7 +10,10 @@ import {
|
||||
ResolverArgs,
|
||||
ResolverArgsType,
|
||||
} from 'src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface';
|
||||
import { RecordFilter } from 'src/engine/api/graphql/workspace-query-builder/interfaces/record.interface';
|
||||
import {
|
||||
Record,
|
||||
RecordFilter,
|
||||
} from 'src/engine/api/graphql/workspace-query-builder/interfaces/record.interface';
|
||||
|
||||
import { FieldMetadataType } from 'src/engine/metadata-modules/field-metadata/field-metadata.entity';
|
||||
import { hasPositionField } from 'src/engine/metadata-modules/object-metadata/utils/has-position-field.util';
|
||||
@ -47,12 +50,12 @@ export class QueryRunnerArgsFactory {
|
||||
return {
|
||||
...args,
|
||||
data: await Promise.all(
|
||||
(args as CreateManyResolverArgs).data.map((arg, index) =>
|
||||
(args as CreateManyResolverArgs).data?.map((arg, index) =>
|
||||
this.overrideDataByFieldMetadata(arg, options, fieldMetadataMap, {
|
||||
argIndex: index,
|
||||
shouldBackfillPosition,
|
||||
}),
|
||||
),
|
||||
) ?? [],
|
||||
),
|
||||
} satisfies CreateManyResolverArgs;
|
||||
case ResolverArgsType.FindOne:
|
||||
@ -75,25 +78,27 @@ export class QueryRunnerArgsFactory {
|
||||
case ResolverArgsType.FindDuplicates:
|
||||
return {
|
||||
...args,
|
||||
id: await this.overrideValueByFieldMetadata(
|
||||
'id',
|
||||
(args as FindDuplicatesResolverArgs).id,
|
||||
fieldMetadataMap,
|
||||
ids: (await Promise.all(
|
||||
(args as FindDuplicatesResolverArgs).ids?.map((id) =>
|
||||
this.overrideValueByFieldMetadata('id', id, fieldMetadataMap),
|
||||
) ?? [],
|
||||
)) as string[],
|
||||
data: await Promise.all(
|
||||
(args as FindDuplicatesResolverArgs).data?.map((arg, index) =>
|
||||
this.overrideDataByFieldMetadata(arg, options, fieldMetadataMap, {
|
||||
argIndex: index,
|
||||
shouldBackfillPosition,
|
||||
}),
|
||||
) ?? [],
|
||||
),
|
||||
data: await this.overrideDataByFieldMetadata(
|
||||
(args as FindDuplicatesResolverArgs).data,
|
||||
options,
|
||||
fieldMetadataMap,
|
||||
{ shouldBackfillPosition: false },
|
||||
),
|
||||
};
|
||||
} satisfies FindDuplicatesResolverArgs;
|
||||
default:
|
||||
return args;
|
||||
}
|
||||
}
|
||||
|
||||
private async overrideDataByFieldMetadata(
|
||||
data: Record<string, any> | undefined,
|
||||
data: Partial<Record> | undefined,
|
||||
options: WorkspaceQueryRunnerOptions,
|
||||
fieldMetadataMap: Map<string, FieldMetadataInterface>,
|
||||
argPositionBackfillInput: ArgPositionBackfillInput,
|
||||
|
||||
@ -10,6 +10,7 @@ import { ObjectMetadataRepositoryModule } from 'src/engine/object-metadata-repos
|
||||
import { TelemetryListener } from 'src/engine/api/graphql/workspace-query-runner/listeners/telemetry.listener';
|
||||
import { AnalyticsModule } from 'src/engine/core-modules/analytics/analytics.module';
|
||||
import { RecordPositionBackfillCommand } from 'src/engine/api/graphql/workspace-query-runner/commands/0-20-record-position-backfill.command';
|
||||
import { DuplicateModule } from 'src/engine/core-modules/duplicate/duplicate.module';
|
||||
|
||||
import { WorkspaceQueryRunnerService } from './workspace-query-runner.service';
|
||||
|
||||
@ -23,6 +24,7 @@ import { EntityEventsToDbListener } from './listeners/entity-events-to-db.listen
|
||||
WorkspaceQueryHookModule,
|
||||
ObjectMetadataRepositoryModule.forFeature([WorkspaceMemberWorkspaceEntity]),
|
||||
AnalyticsModule,
|
||||
DuplicateModule,
|
||||
],
|
||||
providers: [
|
||||
WorkspaceQueryRunnerService,
|
||||
|
||||
@ -52,6 +52,7 @@ import { STANDARD_OBJECT_IDS } from 'src/engine/workspace-manager/workspace-sync
|
||||
import { assertIsValidUuid } from 'src/engine/api/graphql/workspace-query-runner/utils/assert-is-valid-uuid.util';
|
||||
import { isQueryTimeoutError } from 'src/engine/utils/query-timeout.util';
|
||||
import { InjectMessageQueue } from 'src/engine/integrations/message-queue/decorators/message-queue.decorator';
|
||||
import { DuplicateService } from 'src/engine/core-modules/duplicate/duplicate.service';
|
||||
|
||||
import { WorkspaceQueryRunnerOptions } from './interfaces/query-runner-option.interface';
|
||||
import {
|
||||
@ -77,6 +78,7 @@ export class WorkspaceQueryRunnerService {
|
||||
private readonly eventEmitter: EventEmitter2,
|
||||
private readonly workspaceQueryHookService: WorkspaceQueryHookService,
|
||||
private readonly environmentService: EnvironmentService,
|
||||
private readonly duplicateService: DuplicateService,
|
||||
) {}
|
||||
|
||||
async findMany<
|
||||
@ -167,16 +169,16 @@ export class WorkspaceQueryRunnerService {
|
||||
}
|
||||
|
||||
async findDuplicates<TRecord extends IRecord = IRecord>(
|
||||
args: FindDuplicatesResolverArgs<TRecord>,
|
||||
args: FindDuplicatesResolverArgs<Partial<TRecord>>,
|
||||
options: WorkspaceQueryRunnerOptions,
|
||||
): Promise<IConnection<TRecord> | undefined> {
|
||||
if (!args.data && !args.id) {
|
||||
if (!args.data && !args.ids) {
|
||||
throw new BadRequestException(
|
||||
'You have to provide either "data" or "id" argument',
|
||||
);
|
||||
}
|
||||
|
||||
if (!args.id && isEmpty(args.data)) {
|
||||
if (!args.ids && isEmpty(args.data)) {
|
||||
throw new BadRequestException(
|
||||
'The "data" condition can not be empty when ID input not provided',
|
||||
);
|
||||
@ -190,37 +192,24 @@ export class WorkspaceQueryRunnerService {
|
||||
ResolverArgsType.FindDuplicates,
|
||||
)) as FindDuplicatesResolverArgs<TRecord>;
|
||||
|
||||
let existingRecord: Record<string, unknown> | undefined;
|
||||
let existingRecords: IRecord[] | undefined = undefined;
|
||||
|
||||
if (computedArgs.id) {
|
||||
const existingRecordQuery =
|
||||
this.workspaceQueryBuilderFactory.findDuplicatesExistingRecord(
|
||||
computedArgs.id,
|
||||
options,
|
||||
);
|
||||
|
||||
const existingRecordResult = await this.execute(
|
||||
existingRecordQuery,
|
||||
if (computedArgs.ids && computedArgs.ids.length > 0) {
|
||||
existingRecords = await this.duplicateService.findExistingRecords(
|
||||
computedArgs.ids,
|
||||
objectMetadataItem,
|
||||
workspaceId,
|
||||
);
|
||||
|
||||
const parsedResult = await this.parseResult<Record<string, unknown>>(
|
||||
existingRecordResult,
|
||||
objectMetadataItem,
|
||||
'',
|
||||
);
|
||||
|
||||
existingRecord = parsedResult?.edges?.[0]?.node;
|
||||
|
||||
if (!existingRecord) {
|
||||
throw new NotFoundError(`Object with id ${args.id} not found`);
|
||||
if (!existingRecords || existingRecords.length === 0) {
|
||||
throw new NotFoundError(`Object with id ${args.ids} not found`);
|
||||
}
|
||||
}
|
||||
|
||||
const query = await this.workspaceQueryBuilderFactory.findDuplicates(
|
||||
computedArgs,
|
||||
options,
|
||||
existingRecord,
|
||||
existingRecords,
|
||||
);
|
||||
|
||||
await this.workspaceQueryHookService.executePreQueryHooks(
|
||||
@ -237,17 +226,22 @@ export class WorkspaceQueryRunnerService {
|
||||
result,
|
||||
objectMetadataItem,
|
||||
'',
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
async createMany<Record extends IRecord = IRecord>(
|
||||
args: CreateManyResolverArgs<Record>,
|
||||
args: CreateManyResolverArgs<Partial<Record>>,
|
||||
options: WorkspaceQueryRunnerOptions,
|
||||
): Promise<Record[] | undefined> {
|
||||
const { workspaceId, userId, objectMetadataItem } = options;
|
||||
|
||||
assertMutationNotOnRemoteObject(objectMetadataItem);
|
||||
|
||||
if (args.upsert) {
|
||||
return await this.upsertMany(args, options);
|
||||
}
|
||||
|
||||
args.data.forEach((record) => {
|
||||
if (record?.id) {
|
||||
assertIsValidUuid(record.id);
|
||||
@ -305,17 +299,73 @@ export class WorkspaceQueryRunnerService {
|
||||
return parsedResults;
|
||||
}
|
||||
|
||||
async upsertMany<Record extends IRecord = IRecord>(
|
||||
args: CreateManyResolverArgs<Partial<Record>>,
|
||||
options: WorkspaceQueryRunnerOptions,
|
||||
): Promise<Record[] | undefined> {
|
||||
const ids = args.data
|
||||
.map((item) => item.id)
|
||||
.filter((id) => id !== undefined);
|
||||
|
||||
const existingRecords =
|
||||
ids.length > 0
|
||||
? await this.duplicateService.findExistingRecords(
|
||||
ids as string[],
|
||||
options.objectMetadataItem,
|
||||
options.workspaceId,
|
||||
)
|
||||
: [];
|
||||
|
||||
const existingRecordsMap = new Map(
|
||||
existingRecords.map((record) => [record.id, record]),
|
||||
);
|
||||
|
||||
const results: Record[] = [];
|
||||
const recordsToCreate: Partial<Record>[] = [];
|
||||
|
||||
for (const payload of args.data) {
|
||||
if (payload.id && existingRecordsMap.has(payload.id)) {
|
||||
const result = await this.updateOne(
|
||||
{ id: payload.id, data: payload },
|
||||
options,
|
||||
);
|
||||
|
||||
if (result) {
|
||||
results.push(result);
|
||||
}
|
||||
} else {
|
||||
recordsToCreate.push(payload);
|
||||
}
|
||||
}
|
||||
|
||||
if (recordsToCreate.length > 0) {
|
||||
const createResults = await this.createMany(
|
||||
{ data: recordsToCreate } as CreateManyResolverArgs<Partial<Record>>,
|
||||
options,
|
||||
);
|
||||
|
||||
if (createResults) {
|
||||
results.push(...createResults);
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
async createOne<Record extends IRecord = IRecord>(
|
||||
args: CreateOneResolverArgs<Record>,
|
||||
args: CreateOneResolverArgs<Partial<Record>>,
|
||||
options: WorkspaceQueryRunnerOptions,
|
||||
): Promise<Record | undefined> {
|
||||
const results = await this.createMany({ data: [args.data] }, options);
|
||||
const results = await this.createMany(
|
||||
{ data: [args.data], upsert: args.upsert },
|
||||
options,
|
||||
);
|
||||
|
||||
return results?.[0];
|
||||
}
|
||||
|
||||
async updateOne<Record extends IRecord = IRecord>(
|
||||
args: UpdateOneResolverArgs<Record>,
|
||||
args: UpdateOneResolverArgs<Partial<Record>>,
|
||||
options: WorkspaceQueryRunnerOptions,
|
||||
): Promise<Record | undefined> {
|
||||
const { workspaceId, userId, objectMetadataItem } = options;
|
||||
@ -373,7 +423,7 @@ export class WorkspaceQueryRunnerService {
|
||||
}
|
||||
|
||||
async updateMany<Record extends IRecord = IRecord>(
|
||||
args: UpdateManyResolverArgs<Record>,
|
||||
args: UpdateManyResolverArgs<Partial<Record>>,
|
||||
options: WorkspaceQueryRunnerOptions,
|
||||
): Promise<Record[] | undefined> {
|
||||
const { userId, workspaceId, objectMetadataItem } = options;
|
||||
@ -609,11 +659,21 @@ export class WorkspaceQueryRunnerService {
|
||||
graphqlResult: PGGraphQLResult | undefined,
|
||||
objectMetadataItem: ObjectMetadataInterface,
|
||||
command: string,
|
||||
isMultiQuery = false,
|
||||
): Promise<Result> {
|
||||
const entityKey = `${command}${computeObjectTargetTable(
|
||||
objectMetadataItem,
|
||||
)}Collection`;
|
||||
const result = graphqlResult?.[0]?.resolve?.data?.[entityKey];
|
||||
const result = !isMultiQuery
|
||||
? graphqlResult?.[0]?.resolve?.data?.[entityKey]
|
||||
: Object.keys(graphqlResult?.[0]?.resolve?.data).reduce(
|
||||
(acc: IRecord[], dataItem, index) => {
|
||||
acc.push(graphqlResult?.[0]?.resolve?.data[`${entityKey}${index}`]);
|
||||
|
||||
return acc;
|
||||
},
|
||||
[],
|
||||
);
|
||||
const errors = graphqlResult?.[0]?.resolve?.errors;
|
||||
|
||||
if (
|
||||
|
||||
@ -1,30 +0,0 @@
|
||||
import { RecordDuplicateCriteria } from 'src/engine/api/graphql/workspace-query-builder/interfaces/record.interface';
|
||||
|
||||
/**
|
||||
* objectName: directly reference the name of the object from the metadata tables.
|
||||
* columnNames: reference the column names not the field names.
|
||||
* So if we need to reference a custom field, we should directly add the column name like `_customColumn`.
|
||||
* If we need to terence a composite field, we should add all children of the composite like `nameFirstName` and `nameLastName`
|
||||
*/
|
||||
export const DUPLICATE_CRITERIA_COLLECTION: RecordDuplicateCriteria[] = [
|
||||
{
|
||||
objectName: 'company',
|
||||
columnNames: ['domainName'],
|
||||
},
|
||||
{
|
||||
objectName: 'company',
|
||||
columnNames: ['name'],
|
||||
},
|
||||
{
|
||||
objectName: 'person',
|
||||
columnNames: ['nameFirstName', 'nameLastName'],
|
||||
},
|
||||
{
|
||||
objectName: 'person',
|
||||
columnNames: ['linkedinLinkUrl'],
|
||||
},
|
||||
{
|
||||
objectName: 'person',
|
||||
columnNames: ['email'],
|
||||
},
|
||||
];
|
||||
@ -39,26 +39,36 @@ export interface FindOneResolverArgs<Filter = any> {
|
||||
filter?: Filter;
|
||||
}
|
||||
|
||||
export interface FindDuplicatesResolverArgs<Data extends Record = Record> {
|
||||
id?: string;
|
||||
data?: Data;
|
||||
export interface FindDuplicatesResolverArgs<
|
||||
Data extends Partial<Record> = Partial<Record>,
|
||||
> {
|
||||
ids?: string[];
|
||||
data?: Data[];
|
||||
}
|
||||
|
||||
export interface CreateOneResolverArgs<Data extends Record = Record> {
|
||||
export interface CreateOneResolverArgs<
|
||||
Data extends Partial<Record> = Partial<Record>,
|
||||
> {
|
||||
data: Data;
|
||||
upsert?: boolean;
|
||||
}
|
||||
|
||||
export interface CreateManyResolverArgs<Data extends Record = Record> {
|
||||
export interface CreateManyResolverArgs<
|
||||
Data extends Partial<Record> = Partial<Record>,
|
||||
> {
|
||||
data: Data[];
|
||||
upsert?: boolean;
|
||||
}
|
||||
|
||||
export interface UpdateOneResolverArgs<Data extends Record = Record> {
|
||||
export interface UpdateOneResolverArgs<
|
||||
Data extends Partial<Record> = Partial<Record>,
|
||||
> {
|
||||
id: string;
|
||||
data: Data;
|
||||
}
|
||||
|
||||
export interface UpdateManyResolverArgs<
|
||||
Data extends Record = Record,
|
||||
Data extends Partial<Record> = Partial<Record>,
|
||||
Filter = any,
|
||||
> {
|
||||
filter: Filter;
|
||||
|
||||
@ -102,9 +102,12 @@ export class RootTypeFactory {
|
||||
}
|
||||
|
||||
const outputType = this.typeMapperService.mapToGqlType(objectType, {
|
||||
isArray: ['updateMany', 'deleteMany', 'createMany'].includes(
|
||||
methodName,
|
||||
),
|
||||
isArray: [
|
||||
'updateMany',
|
||||
'deleteMany',
|
||||
'createMany',
|
||||
'findDuplicates',
|
||||
].includes(methodName),
|
||||
});
|
||||
|
||||
fieldConfigMap[name] = {
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { GraphQLID, GraphQLInt, GraphQLString } from 'graphql';
|
||||
import { GraphQLBoolean, GraphQLID, GraphQLInt, GraphQLString } from 'graphql';
|
||||
|
||||
import { WorkspaceResolverBuilderMethodNames } from 'src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface';
|
||||
|
||||
@ -29,9 +29,19 @@ describe('getResolverArgs', () => {
|
||||
isNullable: false,
|
||||
isArray: true,
|
||||
},
|
||||
upsert: {
|
||||
isArray: false,
|
||||
isNullable: true,
|
||||
type: GraphQLBoolean,
|
||||
},
|
||||
},
|
||||
createOne: {
|
||||
data: { kind: InputTypeDefinitionKind.Create, isNullable: false },
|
||||
upsert: {
|
||||
isArray: false,
|
||||
isNullable: true,
|
||||
type: GraphQLBoolean,
|
||||
},
|
||||
},
|
||||
updateOne: {
|
||||
id: { type: GraphQLID, isNullable: false },
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { GraphQLString, GraphQLInt, GraphQLID } from 'graphql';
|
||||
import { GraphQLString, GraphQLInt, GraphQLID, GraphQLBoolean } from 'graphql';
|
||||
|
||||
import { WorkspaceResolverBuilderMethodNames } from 'src/engine/api/graphql/workspace-resolver-builder/interfaces/workspace-resolvers-builder.interface';
|
||||
import { ArgMetadata } from 'src/engine/api/graphql/workspace-schema-builder/interfaces/param-metadata.interface';
|
||||
@ -56,6 +56,11 @@ export const getResolverArgs = (
|
||||
isNullable: false,
|
||||
isArray: true,
|
||||
},
|
||||
upsert: {
|
||||
type: GraphQLBoolean,
|
||||
isNullable: true,
|
||||
isArray: false,
|
||||
},
|
||||
};
|
||||
case 'createOne':
|
||||
return {
|
||||
@ -63,6 +68,11 @@ export const getResolverArgs = (
|
||||
kind: InputTypeDefinitionKind.Create,
|
||||
isNullable: false,
|
||||
},
|
||||
upsert: {
|
||||
type: GraphQLBoolean,
|
||||
isNullable: true,
|
||||
isArray: false,
|
||||
},
|
||||
};
|
||||
case 'updateOne':
|
||||
return {
|
||||
@ -77,13 +87,15 @@ export const getResolverArgs = (
|
||||
};
|
||||
case 'findDuplicates':
|
||||
return {
|
||||
id: {
|
||||
ids: {
|
||||
type: GraphQLID,
|
||||
isNullable: true,
|
||||
isArray: true,
|
||||
},
|
||||
data: {
|
||||
kind: InputTypeDefinitionKind.Create,
|
||||
isNullable: true,
|
||||
isArray: true,
|
||||
},
|
||||
};
|
||||
case 'deleteOne':
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
|
||||
import { ObjectMetadataInterface } from 'src/engine/metadata-modules/field-metadata/interfaces/object-metadata.interface';
|
||||
import { Record } from 'src/engine/api/graphql/workspace-query-builder/interfaces/record.interface';
|
||||
|
||||
import { compositeTypeDefintions } from 'src/engine/metadata-modules/field-metadata/composite-types';
|
||||
import { isCompositeFieldMetadataType } from 'src/engine/metadata-modules/field-metadata/utils/is-composite-field-metadata-type.util';
|
||||
@ -8,7 +9,7 @@ import { computeObjectTargetTable } from 'src/engine/utils/compute-object-target
|
||||
|
||||
export const checkArrayFields = (
|
||||
objectMetadata: ObjectMetadataInterface,
|
||||
fields: Array<Record<string, any>>,
|
||||
fields: Array<Partial<Record>>,
|
||||
): void => {
|
||||
const fieldMetadataNames = objectMetadata.fields
|
||||
.map((field) => {
|
||||
|
||||
Reference in New Issue
Block a user