Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(segment): support templating for segment live query #1235

Merged
merged 1 commit into from
Jan 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion packages/agent/src/routes/access/count.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@ export default class CountRoute extends CollectionRoute {
if (this.collection.schema.countable) {
const scope = await this.services.authorization.getScope(this.collection, context);
const caller = QueryStringParser.parseCaller(context);
const filter = ContextFilterFactory.build(this.collection, context, scope);
let filter = ContextFilterFactory.build(this.collection, context, scope);
filter = await this.services.segmentQueryHandler.handleLiveQuerySegmentFilter(
context,
filter,
);

const aggregation = new Aggregation({ operation: 'Count' });
const aggregationResult = await this.collection.aggregate(caller, filter, aggregation);
Expand Down
6 changes: 5 additions & 1 deletion packages/agent/src/routes/access/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,11 @@ export default class ListRoute extends CollectionRoute {
await this.services.authorization.assertCanBrowse(context, this.collection.name);

const scope = await this.services.authorization.getScope(this.collection, context);
const paginatedFilter = ContextFilterFactory.buildPaginated(this.collection, context, scope);
let paginatedFilter = ContextFilterFactory.buildPaginated(this.collection, context, scope);
paginatedFilter = await this.services.segmentQueryHandler.handleLiveQuerySegmentFilter(
context,
paginatedFilter,
);

const records = await this.collection.list(
QueryStringParser.parseCaller(context),
Expand Down
5 changes: 5 additions & 0 deletions packages/agent/src/services/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,24 @@ import { ChartHandlerInterface } from '@forestadmin/forestadmin-client';

import authorizationServiceFactory from './authorization';
import AuthorizationService from './authorization/authorization';
import SegmentQueryHandler from './segment-query-handler';
import Serializer from './serializer';
import { AgentOptionsWithDefaults } from '../types';

export type ForestAdminHttpDriverServices = {
serializer: Serializer;
authorization: AuthorizationService;
chartHandler: ChartHandlerInterface;
segmentQueryHandler: SegmentQueryHandler;
};

export default (options: AgentOptionsWithDefaults): ForestAdminHttpDriverServices => {
return {
authorization: authorizationServiceFactory(options),
serializer: new Serializer(),
chartHandler: options.forestAdminClient.chartHandler,
segmentQueryHandler: new SegmentQueryHandler(
options.forestAdminClient.contextVariablesInstantiator,
),
};
};
47 changes: 47 additions & 0 deletions packages/agent/src/services/segment-query-handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import type { Caller, PaginatedFilter } from '@forestadmin/datasource-toolkit';
import type { ContextVariablesInstantiatorInterface } from '@forestadmin/forestadmin-client';

import { ContextVariablesInjector } from '@forestadmin/forestadmin-client';
import { Context } from 'koa';

export default class SegmentQueryHandler {
private readonly contextVariablesInstantiator: ContextVariablesInstantiatorInterface;

constructor(contextVariablesInstantiator: ContextVariablesInstantiatorInterface) {
this.contextVariablesInstantiator = contextVariablesInstantiator;
}

public async handleLiveQuerySegmentFilter(context: Context, paginatedFilter: PaginatedFilter) {
if (paginatedFilter.liveQuerySegment) {
const { renderingId, id: userId } = <Caller>context.state.user;
const contextVariables = await this.contextVariablesInstantiator.buildContextVariables({
userId,
renderingId,
});
const contextVariablesUsed: Record<string, unknown> = {};

const replaceContextVariable = (contextVariableName: string) => {
const contextVariableRenamed = contextVariableName.replace(/\./g, '_');
contextVariablesUsed[contextVariableRenamed] =
contextVariables.getValue(contextVariableName);

return `$${contextVariableRenamed}`;
};

const replacedQuery = ContextVariablesInjector.injectContextInValueCustom(
paginatedFilter.liveQuerySegment.query,
replaceContextVariable,
);

return paginatedFilter.override({
liveQuerySegment: {
query: replacedQuery,
contextVariables: contextVariablesUsed,
connectionName: paginatedFilter.liveQuerySegment.connectionName,
},
});
}

return paginatedFilter;
}
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { Factory } from 'fishery';

import factoryAuthorization from './authorization/authorization';
import factorySegmentQueryHandler from './segment-query-handler';
import factorySerializer from './serializer';
import { ForestAdminHttpDriverServices } from '../../src/services';

export default Factory.define<ForestAdminHttpDriverServices>(() => ({
serializer: factorySerializer.build(),
authorization: factoryAuthorization.mockAllMethods().build(),
segmentQueryHandler: factorySegmentQueryHandler.build(),
chartHandler: {
getChartWithContextInjected: jest.fn(),
getQueryForChart: jest.fn(),
Expand Down
7 changes: 7 additions & 0 deletions packages/agent/test/__factories__/segment-query-handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Factory } from 'fishery';

import SegmentQueryHandler from '../../src/services/segment-query-handler';

export default Factory.define<SegmentQueryHandler>(
() => new SegmentQueryHandler({ buildContextVariables: jest.fn().mockResolvedValue({}) }),
);
58 changes: 58 additions & 0 deletions packages/agent/test/services/segment-query-handler.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { PaginatedFilter } from '@forestadmin/datasource-toolkit';
import { Context } from 'koa';

import SegmentQueryHandler from '../../src/services/segment-query-handler';

describe('SegmentQueryHandler', () => {
const spyBuildContextVariables = jest.fn().mockResolvedValue({});

const setupService = (): SegmentQueryHandler => {
return new SegmentQueryHandler({ buildContextVariables: spyBuildContextVariables });
};

afterEach(() => jest.resetAllMocks());

describe('when no liveQuerySegment is defined', () => {
test('should do nothing', async () => {
const context = {
state: { user: {} },
} as Context;
const paginatedFilter = new PaginatedFilter({});

const service = setupService();

const result = await service.handleLiveQuerySegmentFilter(context, paginatedFilter);
expect(spyBuildContextVariables).not.toHaveBeenCalled();
expect(result).toStrictEqual(paginatedFilter);
});
});

describe('when liveQuerySegment is defined', () => {
test('should handle the live query', async () => {
const context = {
state: { user: { id: 42, renderingId: 101 } },
} as Context;
const paginatedFilter = new PaginatedFilter({
liveQuerySegment: {
query: 'SELECT id FROM "users" WHERE email like {{currentUser.email}};',
connectionName: 'main',
},
});

spyBuildContextVariables.mockResolvedValue({ getValue: () => 'johndoe@forestadmin.com' });
const service = setupService();

const result = await service.handleLiveQuerySegmentFilter(context, paginatedFilter);
expect(spyBuildContextVariables).toHaveBeenCalled();
expect(result).toStrictEqual(
paginatedFilter.override({
liveQuerySegment: {
query: 'SELECT id FROM "users" WHERE email like $currentUser_email;',
contextVariables: { currentUser_email: 'johndoe@forestadmin.com' },
connectionName: 'main',
},
}),
);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,13 @@ export default class SegmentCollectionDecorator extends CollectionDecorator {
const { liveQuerySegment } = filter;

if (liveQuerySegment) {
const { query, connectionName } = liveQuerySegment;
const { query, connectionName, contextVariables } = liveQuerySegment;

try {
const result = (await this.dataSource.executeNativeQuery(
connectionName,
query,
{},
contextVariables,
)) as Record<string, unknown>[];

const [primaryKey] = SchemaUtils.getPrimaryKeys(this.childCollection.schema);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,11 @@ describe('SegmentCollectionDecorator', () => {
const filter = await segmentDecorator.refineFilter(
factories.caller.build(),
factories.filter.build({
liveQuerySegment: { query: 'SELECT id from toto', connectionName: 'main' },
liveQuerySegment: {
query: 'SELECT id from toto',
connectionName: 'main',
contextVariables: { toto: 1 },
},
}),
);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
import ConditionTree, { PlainConditionTree } from '../condition-tree/nodes/base';

export type LiveQuerySegment = {
query: string;
connectionName: string;
contextVariables?: Record<string, unknown>;
};

export type FilterComponents = {
conditionTree?: ConditionTree;
search?: string | null;
searchExtended?: boolean;
segment?: string;
liveQuerySegment?: { query: string; connectionName: string };
liveQuerySegment?: LiveQuerySegment;
};

export type PlainFilter = {
Expand All @@ -20,7 +26,7 @@ export default class Filter {
search?: string;
searchExtended?: boolean;
segment?: string;
liveQuerySegment?: { query: string; connectionName: string };
liveQuerySegment?: LiveQuerySegment;

get isNestable(): boolean {
return !this.search && !this.segment;
Expand Down
Loading