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

Query parameters in all methods #15

Merged
merged 4 commits into from
Jun 29, 2024
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
22 changes: 19 additions & 3 deletions src/GoogleSpreadsheetsOrm.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ParsedSpreadsheetCellValue } from './Query';
import { ParsedSpreadsheetCellValue, Query } from './Query';
import { Serializer } from './serialization/Serializer';
import { GoogleSheetClientProvider } from './GoogleSheetClientProvider';
import { Logger } from './utils/Logger';
Expand Down Expand Up @@ -53,9 +53,9 @@ export class GoogleSpreadsheetsOrm<T extends BaseModel> {
*
* @returns A Promise that resolves to an array of entities of type T, representing all rows retrieved from the sheet.
*/
public async all(): Promise<T[]> {
public async all(options: Query<T> = {}): Promise<T[]> {
const { data, headers } = await this.findSheetData();
return this.rowsToEntities(data, headers);
return this.rowsToEntities(data, headers).filter(entity => this.shouldIncludeRow(options?.filter, entity));
}

/**
Expand Down Expand Up @@ -333,6 +333,22 @@ export class GoogleSpreadsheetsOrm<T extends BaseModel> {
return index + 2;
}

private shouldIncludeRow = (
filters: {
[column in keyof T]?: ParsedSpreadsheetCellValue | ParsedSpreadsheetCellValue[];
} = {},
entity: T,
): boolean =>
Object.entries(filters).every(([entityField, fieldValue]) => {
const entityValue = entity[entityField as keyof T];

if (Array.isArray(fieldValue)) {
return fieldValue.includes(entityValue);
}

return entityValue === fieldValue;
});

private toSheetArrayFromHeaders(entity: T, headers: string[]): ParsedSpreadsheetCellValue[] {
return headers.map(header => {
const castingType: string | undefined = this.options?.castings?.[header as keyof T];
Expand Down
14 changes: 9 additions & 5 deletions src/Query.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
export type ParsedSpreadsheetCellValue = string | number | boolean | Date | object;
export type ParsedSpreadsheetCellValue = string | number | boolean | Date;

export type Query<T> = {
[column in keyof T]?: ParsedSpreadsheetCellValue;
filter?: {
[column in keyof T]?: ParsedSpreadsheetCellValue | ParsedSpreadsheetCellValue[];
};
// paging?: PagingQuery;
};

export type InQuery<T> = {
[column in keyof T]?: ParsedSpreadsheetCellValue[];
};
// export type PagingQuery = {
// from?: number;
// to?: number;
// };
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export * from './GoogleSpreadsheetsOrm';
export * from './Options';
export * from './Castings';
export * from './Query';
export { BaseModel } from './BaseModel';
export { MetricOperation } from './metrics/MetricOperation';
export { CacheProvider } from './cache/CacheProvider';
132 changes: 132 additions & 0 deletions tests/GoogleSpreadsheetsOrm.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,138 @@ describe(GoogleSpreadsheetsOrm.name, () => {
});
});

test('all should correctly query rows', async () => {
const rawValues = [
['id', 'createdAt', 'name', 'jsonField', 'current', 'year'],
[
'ae222b54-182f-4958-b77f-26a3a04dff32',
'13/10/2022 08:11:23',
'John Doe',
'[1, 2, 3, 4, 5, 6]',
'false',
'2023',
],
[
'ae222b54-182f-4958-b77f-26a3a04dff33',
'29/12/2023 17:47:04',
'Donh Joe',
// language=json
'{ "a": { "b": "c" } }',
'true',
'',
],
['ae222b54-182f-4958-b77f-26a3a04dff34', '29/12/2023 17:47:04', 'Donh Joe 2', '{}', '', undefined],
['ae222b54-182f-4958-b77f-26a3a04dff35', '29/12/2023 17:47:04', 'Donh Joe 3', '{}', 'true', '2023'],
];

sheetClients
.map(s => s.spreadsheets.values as MockProxy<sheets_v4.Resource$Spreadsheets$Values>)
.forEach(mockValuesClient =>
mockValuesClient.get.mockResolvedValue({
data: {
values: rawValues,
},
} as never),
);

const entities = await sut.all({
filter: {
current: true,
},
});

const expectedValues: TestEntity[] = [
{
id: 'ae222b54-182f-4958-b77f-26a3a04dff33',
createdAt: new Date('2023-12-29 17:47:04'),
name: 'Donh Joe',
jsonField: { a: { b: 'c' } },
current: true,
year: undefined,
},
{
id: 'ae222b54-182f-4958-b77f-26a3a04dff35',
createdAt: new Date('2023-12-29 17:47:04'),
name: 'Donh Joe 3',
jsonField: {},
current: true,
year: 2023,
},
];
expect(entities).toStrictEqual(expectedValues);
expect(sut.metrics()).toMatchObject({
[MetricOperation.FETCH_SHEET_DATA]: [
expect.any(Number), // Just one call
],
});
});

test('all should correctly IN query rows', async () => {
const rawValues = [
['id', 'createdAt', 'name', 'jsonField', 'current', 'year'],
[
'ae222b54-182f-4958-b77f-26a3a04dff32',
'13/10/2022 08:11:23',
'John Doe',
'[1, 2, 3, 4, 5, 6]',
'false',
'2023',
],
[
'ae222b54-182f-4958-b77f-26a3a04dff33',
'29/12/2023 17:47:04',
'Donh Joe',
// language=json
'{ "a": { "b": "c" } }',
'true',
'',
],
['ae222b54-182f-4958-b77f-26a3a04dff34', '29/12/2023 17:47:04', 'Donh Joe 2', '{}', '', undefined],
['ae222b54-182f-4958-b77f-26a3a04dff35', '29/12/2023 17:47:04', 'Donh Joe 3', '{}', 'true', '2023'],
];

sheetClients
.map(s => s.spreadsheets.values as MockProxy<sheets_v4.Resource$Spreadsheets$Values>)
.forEach(mockValuesClient =>
mockValuesClient.get.mockResolvedValue({
data: {
values: rawValues,
},
} as never),
);

const entities = await sut.all({
filter: {
id: ['ae222b54-182f-4958-b77f-26a3a04dff32', 'ae222b54-182f-4958-b77f-26a3a04dff33'],
},
});

const expectedValues: TestEntity[] = [
{
id: 'ae222b54-182f-4958-b77f-26a3a04dff32',
createdAt: new Date('2022-10-13 08:11:23'),
name: 'John Doe',
jsonField: [1, 2, 3, 4, 5, 6],
current: false,
year: 2023,
},
{
id: 'ae222b54-182f-4958-b77f-26a3a04dff33',
createdAt: new Date('2023-12-29 17:47:04'),
name: 'Donh Joe',
jsonField: { a: { b: 'c' } },
current: true,
year: undefined,
},
];
expect(entities).toStrictEqual(expectedValues);
expect(sut.metrics()).toMatchObject({
[MetricOperation.FETCH_SHEET_DATA]: [
expect.any(Number), // Just one call
],
});
});

test('create method should insert a new row', async () => {
// Configure table headers, so that save method can correctly match headers positions.
const rawValues = [['id', 'createdAt', 'name', 'jsonField', 'current', 'year']];
Expand Down
Loading