mirror of
https://github.com/hasura/graphql-engine.git
synced 2024-12-14 17:02:49 +03:00
feature (console): get table rows for non postgres databases via DAL
PR-URL: https://github.com/hasura/graphql-engine-mono/pull/6022 GitOrigin-RevId: 89251ad91f2c54ae109f160bb141a40704d30fb7
This commit is contained in:
parent
a9f7c1ef80
commit
68220df842
@ -1,10 +1,104 @@
|
|||||||
import { renderHook } from '@testing-library/react-hooks';
|
import { renderHook } from '@testing-library/react-hooks';
|
||||||
|
import { rest } from 'msw';
|
||||||
|
import { setupServer } from 'msw/node';
|
||||||
import { wrapper } from '../../../../../hooks/__tests__/common/decorator';
|
import { wrapper } from '../../../../../hooks/__tests__/common/decorator';
|
||||||
import { useRows } from '.';
|
import { useRows } from '.';
|
||||||
import { server, postgresTableMockData } from '../mocks/handlers.mock';
|
|
||||||
import { UseRowsPropType } from './useRows';
|
import { UseRowsPropType } from './useRows';
|
||||||
|
import { TableRow } from '../../../../../features/DataSource';
|
||||||
|
import { Metadata } from '../../../../../features/MetadataAPI';
|
||||||
|
|
||||||
|
describe('Postgres browse rows data', () => {
|
||||||
|
const mockMetadata: Metadata = {
|
||||||
|
resource_version: 54,
|
||||||
|
metadata: {
|
||||||
|
version: 3,
|
||||||
|
sources: [
|
||||||
|
{
|
||||||
|
name: 'chinook',
|
||||||
|
kind: 'postgres',
|
||||||
|
tables: [
|
||||||
|
{
|
||||||
|
table: {
|
||||||
|
name: 'Album',
|
||||||
|
schema: 'public',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
configuration: {
|
||||||
|
connection_info: {
|
||||||
|
database_url:
|
||||||
|
'postgres://postgres:test@host.docker.internal:6001/chinook',
|
||||||
|
isolation_level: 'read-committed',
|
||||||
|
use_prepared_statements: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const expectedResult: TableRow[] = [
|
||||||
|
{
|
||||||
|
AlbumId: 225,
|
||||||
|
Title: 'Volume Dois',
|
||||||
|
ArtistId: 146,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
AlbumId: 275,
|
||||||
|
Title: 'Vivaldi: The Four Seasons',
|
||||||
|
ArtistId: 209,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
AlbumId: 114,
|
||||||
|
Title: 'Virtual XI',
|
||||||
|
ArtistId: 90,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
AlbumId: 52,
|
||||||
|
Title: 'Vinícius De Moraes - Sem Limite',
|
||||||
|
ArtistId: 70,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
AlbumId: 247,
|
||||||
|
Title: 'Vinicius De Moraes',
|
||||||
|
ArtistId: 72,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
AlbumId: 67,
|
||||||
|
Title: "Vault: Def Leppard's Greatest Hits",
|
||||||
|
ArtistId: 78,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
AlbumId: 245,
|
||||||
|
Title: 'Van Halen III',
|
||||||
|
ArtistId: 152,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
AlbumId: 244,
|
||||||
|
Title: 'Van Halen',
|
||||||
|
ArtistId: 152,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
AlbumId: 92,
|
||||||
|
Title: 'Use Your Illusion II',
|
||||||
|
ArtistId: 88,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
AlbumId: 91,
|
||||||
|
Title: 'Use Your Illusion I',
|
||||||
|
ArtistId: 88,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const server = setupServer(
|
||||||
|
rest.post('http://localhost/v1/metadata', (req, res, ctx) => {
|
||||||
|
return res(ctx.status(200), ctx.json(mockMetadata));
|
||||||
|
}),
|
||||||
|
rest.post('http://localhost/v2/query', (req, res, ctx) => {
|
||||||
|
return res(ctx.status(200), ctx.json(expectedResult));
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
describe('useRemoveAgent tests: ', () => {
|
|
||||||
beforeAll(() => {
|
beforeAll(() => {
|
||||||
server.listen();
|
server.listen();
|
||||||
});
|
});
|
||||||
@ -18,13 +112,127 @@ describe('useRemoveAgent tests: ', () => {
|
|||||||
table: { name: 'Album', schema: 'public' },
|
table: { name: 'Album', schema: 'public' },
|
||||||
options: {
|
options: {
|
||||||
limit: 10,
|
limit: 10,
|
||||||
where: { $and: [{ AlbumId: { $gt: 4 } }] },
|
where: [{ AlbumId: { $gt: 4 } }],
|
||||||
order_by: [{ column: 'Title', type: 'desc' }],
|
order_by: [{ column: 'Title', type: 'desc' }],
|
||||||
offset: 15,
|
offset: 15,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
const { result, waitFor } = renderHook(() => useRows(props), { wrapper });
|
const { result, waitFor } = renderHook(() => useRows(props), { wrapper });
|
||||||
await waitFor(() => result.current.isSuccess);
|
await waitFor(() => result.current.isSuccess);
|
||||||
expect(result.current.data).toEqual(postgresTableMockData);
|
expect(result.current.data).toEqual(expectedResult);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('MSSQL browse rows', () => {
|
||||||
|
const mockMetadata: Metadata = {
|
||||||
|
resource_version: 54,
|
||||||
|
metadata: {
|
||||||
|
version: 3,
|
||||||
|
sources: [
|
||||||
|
{
|
||||||
|
name: 'bikes',
|
||||||
|
kind: 'mssql',
|
||||||
|
tables: [
|
||||||
|
{
|
||||||
|
table: {
|
||||||
|
name: 'customers',
|
||||||
|
schema: 'sales',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
configuration: {
|
||||||
|
connection_info: {
|
||||||
|
connection_string:
|
||||||
|
'DRIVER={ODBC Driver 17 for SQL Server};SERVER=host.docker.internal;DATABASE=bikes;Uid=SA;Pwd=reallyStrongPwd123',
|
||||||
|
pool_settings: {
|
||||||
|
idle_timeout: 5,
|
||||||
|
max_connections: 50,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const expectedResult: TableRow[] = [
|
||||||
|
{
|
||||||
|
customer_id: 259,
|
||||||
|
order_date: '2016-01-01',
|
||||||
|
order_id: 1,
|
||||||
|
order_status: 4,
|
||||||
|
required_date: '2016-01-03',
|
||||||
|
shipped_date: '2016-01-03',
|
||||||
|
staff_id: 2,
|
||||||
|
store_id: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
customer_id: 1212,
|
||||||
|
order_date: '2016-01-01',
|
||||||
|
order_id: 2,
|
||||||
|
order_status: 4,
|
||||||
|
required_date: '2016-01-04',
|
||||||
|
shipped_date: '2016-01-03',
|
||||||
|
staff_id: 6,
|
||||||
|
store_id: 2,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
customer_id: 523,
|
||||||
|
order_date: '2016-01-02',
|
||||||
|
order_id: 3,
|
||||||
|
order_status: 4,
|
||||||
|
required_date: '2016-01-05',
|
||||||
|
shipped_date: '2016-01-03',
|
||||||
|
staff_id: 7,
|
||||||
|
store_id: 2,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const server = setupServer(
|
||||||
|
rest.post('http://localhost/v1/metadata', (req, res, ctx) => {
|
||||||
|
return res(ctx.status(200), ctx.json(mockMetadata));
|
||||||
|
}),
|
||||||
|
rest.post('http://localhost/v2/query', (req, res, ctx) => {
|
||||||
|
return res(
|
||||||
|
ctx.status(200),
|
||||||
|
ctx.json({
|
||||||
|
result_type: 'TuplesOk',
|
||||||
|
result: [
|
||||||
|
['COLUMN_NAME', 'DATA_TYPE'],
|
||||||
|
['store_id', 'int'],
|
||||||
|
['store_name', 'varchar'],
|
||||||
|
['phone', 'varchar'],
|
||||||
|
['email', 'varchar'],
|
||||||
|
['street', 'varchar'],
|
||||||
|
['city', 'varchar'],
|
||||||
|
['state', 'varchar'],
|
||||||
|
['zip_code', 'varchar'],
|
||||||
|
],
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}),
|
||||||
|
rest.post('http://localhost/v1/graphql', (req, res, ctx) => {
|
||||||
|
return res(
|
||||||
|
ctx.status(200),
|
||||||
|
ctx.json({ data: { sales_customers: expectedResult } })
|
||||||
|
);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
beforeAll(() => {
|
||||||
|
server.listen();
|
||||||
|
});
|
||||||
|
afterAll(() => {
|
||||||
|
server.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns table data for an mssql table', async () => {
|
||||||
|
const props: UseRowsPropType = {
|
||||||
|
dataSourceName: 'bikes',
|
||||||
|
table: { name: 'customers', schema: 'sales' },
|
||||||
|
};
|
||||||
|
const { result, waitFor } = renderHook(() => useRows(props), { wrapper });
|
||||||
|
await waitFor(() => result.current.isSuccess);
|
||||||
|
expect(result.current.data).toEqual(expectedResult);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
@ -28,6 +28,28 @@ export const mockMetadata: Metadata = {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: 'bikes',
|
||||||
|
kind: 'mssql',
|
||||||
|
tables: [
|
||||||
|
{
|
||||||
|
table: {
|
||||||
|
name: 'customers',
|
||||||
|
schema: 'sales',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
configuration: {
|
||||||
|
connection_info: {
|
||||||
|
connection_string:
|
||||||
|
'DRIVER={ODBC Driver 17 for SQL Server};SERVER=host.docker.internal;DATABASE=bikes;Uid=SA;Pwd=reallyStrongPwd123',
|
||||||
|
pool_settings: {
|
||||||
|
idle_timeout: 5,
|
||||||
|
max_connections: 50,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
@ -1,59 +0,0 @@
|
|||||||
import { RunSQLResponse } from '../api';
|
|
||||||
import { IntrospectedTable, TableColumn } from '../types';
|
|
||||||
import { adaptIntrospectedTables, adaptTableColumns } from '../common/utils';
|
|
||||||
|
|
||||||
describe('adaptIntrospectedTables', () => {
|
|
||||||
it('adapts the sql response', () => {
|
|
||||||
const runSqlResponse: RunSQLResponse = {
|
|
||||||
result_type: 'TuplesOk',
|
|
||||||
result: [
|
|
||||||
['table_name', 'table_schema', 'table_type'],
|
|
||||||
['Artist', 'public', 'BASE TABLE'],
|
|
||||||
['Album', 'public', 'BASE TABLE'],
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
const expectedResponse: IntrospectedTable[] = [
|
|
||||||
{
|
|
||||||
name: 'public.Artist',
|
|
||||||
table: {
|
|
||||||
name: 'Artist',
|
|
||||||
schema: 'public',
|
|
||||||
},
|
|
||||||
type: 'BASE TABLE',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: 'public.Album',
|
|
||||||
table: {
|
|
||||||
name: 'Album',
|
|
||||||
schema: 'public',
|
|
||||||
},
|
|
||||||
type: 'BASE TABLE',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
expect(adaptIntrospectedTables(runSqlResponse)).toEqual(expectedResponse);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('adaptTableColumns', () => {
|
|
||||||
it('adapts the sql response', () => {
|
|
||||||
const runSqlResponse: RunSQLResponse = {
|
|
||||||
result_type: 'TuplesOk',
|
|
||||||
result: [
|
|
||||||
['column_name', 'data_type'],
|
|
||||||
['id', 'int'],
|
|
||||||
['name', 'varchar'],
|
|
||||||
['updated_at', 'datetime'],
|
|
||||||
],
|
|
||||||
};
|
|
||||||
|
|
||||||
const expectedResponse: TableColumn[] = [
|
|
||||||
{ name: 'id', dataType: 'int' },
|
|
||||||
{ name: 'name', dataType: 'varchar' },
|
|
||||||
{ name: 'updated_at', dataType: 'datetime' },
|
|
||||||
];
|
|
||||||
|
|
||||||
expect(adaptTableColumns(runSqlResponse.result)).toEqual(expectedResponse);
|
|
||||||
});
|
|
||||||
});
|
|
@ -56,6 +56,22 @@ export const runQuery = async <ResponseType>({
|
|||||||
return result.data;
|
return result.data;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const runGraphQL = async ({
|
||||||
|
operationName,
|
||||||
|
query,
|
||||||
|
httpClient,
|
||||||
|
}: { operationName: string; query: string } & NetworkArgs) => {
|
||||||
|
try {
|
||||||
|
const result = await httpClient.post('v1/graphql', {
|
||||||
|
query,
|
||||||
|
operationName,
|
||||||
|
});
|
||||||
|
return result.data;
|
||||||
|
} catch (err) {
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
export const runSQL = async ({
|
export const runSQL = async ({
|
||||||
source,
|
source,
|
||||||
sql,
|
sql,
|
||||||
|
@ -4,6 +4,7 @@ import {
|
|||||||
getTableColumns,
|
getTableColumns,
|
||||||
getTablesListAsTree,
|
getTablesListAsTree,
|
||||||
} from './introspection';
|
} from './introspection';
|
||||||
|
import { getTableRows } from './query';
|
||||||
|
|
||||||
export type BigQueryTable = { name: string; dataset: string };
|
export type BigQueryTable = { name: string; dataset: string };
|
||||||
|
|
||||||
@ -26,6 +27,6 @@ export const bigquery: Database = {
|
|||||||
getTablesListAsTree,
|
getTablesListAsTree,
|
||||||
},
|
},
|
||||||
query: {
|
query: {
|
||||||
getTableRows: async () => Feature.NotImplemented,
|
getTableRows,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
@ -0,0 +1,62 @@
|
|||||||
|
import { generateGraphQLSelectQuery } from '@/features/GraphQLUtils';
|
||||||
|
import get from 'lodash.get';
|
||||||
|
import { BigQueryTable } from '..';
|
||||||
|
import { exportMetadata, runGraphQL } from '../../api';
|
||||||
|
import { transformGraphqlResponse } from '../../common/utils';
|
||||||
|
import { GetTableRowsProps, TableRow } from '../../types';
|
||||||
|
|
||||||
|
export const getTableRows = async ({
|
||||||
|
table,
|
||||||
|
dataSourceName,
|
||||||
|
httpClient,
|
||||||
|
columns,
|
||||||
|
options,
|
||||||
|
}: GetTableRowsProps): Promise<TableRow[]> => {
|
||||||
|
const { name, dataset } = table as BigQueryTable;
|
||||||
|
|
||||||
|
const source = (await exportMetadata({ httpClient })).metadata.sources.find(
|
||||||
|
({ name: sourceName }) => sourceName === dataSourceName
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If I can't find the source in the metadata, then there is something inconsistent on the server.
|
||||||
|
*/
|
||||||
|
if (!source) throw new Error('getTableRows: source not found in metadata');
|
||||||
|
|
||||||
|
// TODO: I think we can make it better, more generic if we relegate the table comparison thingy to a util function.
|
||||||
|
const trackedTable = source.tables.find(({ table: t }) => {
|
||||||
|
const metadataTableDef = t as BigQueryTable;
|
||||||
|
return (
|
||||||
|
metadataTableDef.name === name && metadataTableDef.dataset === dataset
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!trackedTable)
|
||||||
|
throw new Error('getTableRows: trackedTable not found in metadata');
|
||||||
|
|
||||||
|
const defaultQueryRoot = `${dataset}_${name}`;
|
||||||
|
|
||||||
|
const { query, resultPath } = await generateGraphQLSelectQuery({
|
||||||
|
operationName: 'TableRows',
|
||||||
|
defaultQueryRoot,
|
||||||
|
columns,
|
||||||
|
tableCustomization: trackedTable.configuration,
|
||||||
|
sourceCustomization: source.customization,
|
||||||
|
options,
|
||||||
|
});
|
||||||
|
|
||||||
|
const graphqlResponse = await runGraphQL({
|
||||||
|
operationName: 'TableRows',
|
||||||
|
query,
|
||||||
|
httpClient,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = transformGraphqlResponse({
|
||||||
|
data: get(graphqlResponse.data, resultPath) ?? [],
|
||||||
|
tableCustomization: trackedTable.configuration,
|
||||||
|
sourceCustomization: source.customization,
|
||||||
|
columns,
|
||||||
|
});
|
||||||
|
|
||||||
|
return result;
|
||||||
|
};
|
1
console/src/features/DataSource/bigquery/query/index.ts
Normal file
1
console/src/features/DataSource/bigquery/query/index.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
export { getTableRows } from './getTableRows';
|
@ -7,6 +7,7 @@ import {
|
|||||||
getFKRelationships,
|
getFKRelationships,
|
||||||
getTablesListAsTree,
|
getTablesListAsTree,
|
||||||
} from './introspection';
|
} from './introspection';
|
||||||
|
import { getTableRows } from './query';
|
||||||
|
|
||||||
export type CitusTable = { name: string; schema: string };
|
export type CitusTable = { name: string; schema: string };
|
||||||
|
|
||||||
@ -61,6 +62,6 @@ export const citus: Database = {
|
|||||||
getTablesListAsTree,
|
getTablesListAsTree,
|
||||||
},
|
},
|
||||||
query: {
|
query: {
|
||||||
getTableRows: async () => Feature.NotImplemented,
|
getTableRows,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
60
console/src/features/DataSource/citus/query/getTableRows.ts
Normal file
60
console/src/features/DataSource/citus/query/getTableRows.ts
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
import { generateGraphQLSelectQuery } from '@/features/GraphQLUtils';
|
||||||
|
import get from 'lodash.get';
|
||||||
|
import { CitusTable } from '..';
|
||||||
|
import { exportMetadata, runGraphQL } from '../../api';
|
||||||
|
import { transformGraphqlResponse } from '../../common/utils';
|
||||||
|
import { GetTableRowsProps, TableRow } from '../../types';
|
||||||
|
|
||||||
|
export const getTableRows = async ({
|
||||||
|
table,
|
||||||
|
dataSourceName,
|
||||||
|
httpClient,
|
||||||
|
columns,
|
||||||
|
options,
|
||||||
|
}: GetTableRowsProps): Promise<TableRow[]> => {
|
||||||
|
const { name, schema } = table as CitusTable;
|
||||||
|
|
||||||
|
const source = (await exportMetadata({ httpClient })).metadata.sources.find(
|
||||||
|
({ name: sourceName }) => sourceName === dataSourceName
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If I can't find the source in the metadata, then there is something inconsistent on the server.
|
||||||
|
*/
|
||||||
|
if (!source) throw new Error('getTableRows: source not found in metadata');
|
||||||
|
|
||||||
|
// TODO: I think we can make it better, more generic if we relegate the table comparison thingy to a util function.
|
||||||
|
const trackedTable = source.tables.find(({ table: t }) => {
|
||||||
|
const metadataTableDef = t as CitusTable;
|
||||||
|
return metadataTableDef.name === name && metadataTableDef.schema === schema;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!trackedTable)
|
||||||
|
throw new Error('getTableRows: trackedTable not found in metadata');
|
||||||
|
|
||||||
|
const defaultQueryRoot = schema === 'dbo' ? name : `${schema}_${name}`;
|
||||||
|
|
||||||
|
const { query, resultPath } = await generateGraphQLSelectQuery({
|
||||||
|
operationName: 'TableRows',
|
||||||
|
defaultQueryRoot,
|
||||||
|
columns,
|
||||||
|
tableCustomization: trackedTable.configuration,
|
||||||
|
sourceCustomization: source.customization,
|
||||||
|
options,
|
||||||
|
});
|
||||||
|
|
||||||
|
const graphqlResponse = await runGraphQL({
|
||||||
|
operationName: 'TableRows',
|
||||||
|
query,
|
||||||
|
httpClient,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = transformGraphqlResponse({
|
||||||
|
data: get(graphqlResponse.data, resultPath) ?? [],
|
||||||
|
tableCustomization: trackedTable.configuration,
|
||||||
|
sourceCustomization: source.customization,
|
||||||
|
columns,
|
||||||
|
});
|
||||||
|
|
||||||
|
return result;
|
||||||
|
};
|
1
console/src/features/DataSource/citus/query/index.ts
Normal file
1
console/src/features/DataSource/citus/query/index.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
export { getTableRows } from './getTableRows';
|
@ -7,6 +7,7 @@ import {
|
|||||||
getFKRelationships,
|
getFKRelationships,
|
||||||
getTablesListAsTree,
|
getTablesListAsTree,
|
||||||
} from './introspection';
|
} from './introspection';
|
||||||
|
import { getTableRows } from './query';
|
||||||
|
|
||||||
export type CockroachDBTable = { name: string; schema: string };
|
export type CockroachDBTable = { name: string; schema: string };
|
||||||
|
|
||||||
@ -59,6 +60,6 @@ export const cockroach: Database = {
|
|||||||
getTablesListAsTree,
|
getTablesListAsTree,
|
||||||
},
|
},
|
||||||
query: {
|
query: {
|
||||||
getTableRows: async () => Feature.NotImplemented,
|
getTableRows,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
@ -0,0 +1,60 @@
|
|||||||
|
import { generateGraphQLSelectQuery } from '@/features/GraphQLUtils';
|
||||||
|
import get from 'lodash.get';
|
||||||
|
import { CockroachDBTable } from '..';
|
||||||
|
import { exportMetadata, runGraphQL } from '../../api';
|
||||||
|
import { transformGraphqlResponse } from '../../common/utils';
|
||||||
|
import { GetTableRowsProps, TableRow } from '../../types';
|
||||||
|
|
||||||
|
export const getTableRows = async ({
|
||||||
|
table,
|
||||||
|
dataSourceName,
|
||||||
|
httpClient,
|
||||||
|
columns,
|
||||||
|
options,
|
||||||
|
}: GetTableRowsProps): Promise<TableRow[]> => {
|
||||||
|
const { name, schema } = table as CockroachDBTable;
|
||||||
|
|
||||||
|
const source = (await exportMetadata({ httpClient })).metadata.sources.find(
|
||||||
|
({ name: sourceName }) => sourceName === dataSourceName
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If I can't find the source in the metadata, then there is something inconsistent on the server.
|
||||||
|
*/
|
||||||
|
if (!source) throw new Error('getTableRows: source not found in metadata');
|
||||||
|
|
||||||
|
// TODO: I think we can make it better, more generic if we relegate the table comparison thingy to a util function.
|
||||||
|
const trackedTable = source.tables.find(({ table: t }) => {
|
||||||
|
const metadataTableDef = t as CockroachDBTable;
|
||||||
|
return metadataTableDef.name === name && metadataTableDef.schema === schema;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!trackedTable)
|
||||||
|
throw new Error('getTableRows: trackedTable not found in metadata');
|
||||||
|
|
||||||
|
const defaultQueryRoot = schema === 'dbo' ? name : `${schema}_${name}`;
|
||||||
|
|
||||||
|
const { query, resultPath } = await generateGraphQLSelectQuery({
|
||||||
|
operationName: 'TableRows',
|
||||||
|
defaultQueryRoot,
|
||||||
|
columns,
|
||||||
|
tableCustomization: trackedTable.configuration,
|
||||||
|
sourceCustomization: source.customization,
|
||||||
|
options,
|
||||||
|
});
|
||||||
|
|
||||||
|
const graphqlResponse = await runGraphQL({
|
||||||
|
operationName: 'TableRows',
|
||||||
|
query,
|
||||||
|
httpClient,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = transformGraphqlResponse({
|
||||||
|
data: get(graphqlResponse.data, resultPath) ?? [],
|
||||||
|
tableCustomization: trackedTable.configuration,
|
||||||
|
sourceCustomization: source.customization,
|
||||||
|
columns,
|
||||||
|
});
|
||||||
|
|
||||||
|
return result;
|
||||||
|
};
|
1
console/src/features/DataSource/cockroach/query/index.ts
Normal file
1
console/src/features/DataSource/cockroach/query/index.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
export { getTableRows } from './getTableRows';
|
@ -1,7 +1,7 @@
|
|||||||
import { FaFolder, FaTable } from 'react-icons/fa';
|
import { FaFolder, FaTable } from 'react-icons/fa';
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { Table } from '@/features/MetadataAPI';
|
import { MetadataTable, Source, Table } from '@/features/MetadataAPI';
|
||||||
import { IntrospectedTable, TableColumn } from '../types';
|
import { IntrospectedTable, TableColumn, TableRow } from '../types';
|
||||||
import { RunSQLResponse } from '../api';
|
import { RunSQLResponse } from '../api';
|
||||||
|
|
||||||
export const adaptIntrospectedTables = (
|
export const adaptIntrospectedTables = (
|
||||||
@ -80,3 +80,31 @@ export const convertToTreeData = (
|
|||||||
}),
|
}),
|
||||||
];
|
];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const transformGraphqlResponse = ({
|
||||||
|
data,
|
||||||
|
tableCustomization,
|
||||||
|
}: {
|
||||||
|
data: Record<string, string>[];
|
||||||
|
tableCustomization: MetadataTable['configuration'];
|
||||||
|
sourceCustomization: Source['customization'];
|
||||||
|
columns: string[];
|
||||||
|
}): TableRow[] => {
|
||||||
|
return data.map(row => {
|
||||||
|
const transformedRow = Object.entries(row).reduce((acc, [key, value]) => {
|
||||||
|
const columnName =
|
||||||
|
Object.entries(tableCustomization?.column_config ?? {}).find(
|
||||||
|
([, columnConfig]) => {
|
||||||
|
return columnConfig.custom_name === key;
|
||||||
|
}
|
||||||
|
)?.[0] ?? key;
|
||||||
|
|
||||||
|
return {
|
||||||
|
...acc,
|
||||||
|
[columnName]: value,
|
||||||
|
};
|
||||||
|
}, {});
|
||||||
|
|
||||||
|
return transformedRow;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
@ -5,6 +5,7 @@ import {
|
|||||||
getTableColumns,
|
getTableColumns,
|
||||||
getDatabaseConfiguration,
|
getDatabaseConfiguration,
|
||||||
} from './introspection';
|
} from './introspection';
|
||||||
|
import { getTableRows } from './query';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Why is GDCTable as string[] ?
|
* Why is GDCTable as string[] ?
|
||||||
@ -29,6 +30,6 @@ export const gdc: Database = {
|
|||||||
getTablesListAsTree,
|
getTablesListAsTree,
|
||||||
},
|
},
|
||||||
query: {
|
query: {
|
||||||
getTableRows: async () => Feature.NotImplemented,
|
getTableRows,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
58
console/src/features/DataSource/gdc/query/getTableRows.ts
Normal file
58
console/src/features/DataSource/gdc/query/getTableRows.ts
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
import { generateGraphQLSelectQuery } from '@/features/GraphQLUtils';
|
||||||
|
import get from 'lodash.get';
|
||||||
|
import { GDCTable } from '..';
|
||||||
|
import { exportMetadata, runGraphQL } from '../../api';
|
||||||
|
import { transformGraphqlResponse } from '../../common/utils';
|
||||||
|
import { GetTableRowsProps, TableRow } from '../../types';
|
||||||
|
|
||||||
|
export const getTableRows = async ({
|
||||||
|
table,
|
||||||
|
dataSourceName,
|
||||||
|
httpClient,
|
||||||
|
columns,
|
||||||
|
options,
|
||||||
|
}: GetTableRowsProps): Promise<TableRow[]> => {
|
||||||
|
const source = (await exportMetadata({ httpClient })).metadata.sources.find(
|
||||||
|
({ name: sourceName }) => sourceName === dataSourceName
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If I can't find the source in the metadata, then there is something inconsistent on the server.
|
||||||
|
*/
|
||||||
|
if (!source) throw new Error('getTableRows: source not found in metadata');
|
||||||
|
|
||||||
|
// TODO: I think we can make it better, more generic if we relegate the table comparison thingy to a util function.
|
||||||
|
const trackedTable = source.tables.find(({ table: t }) => {
|
||||||
|
const metadataTableDef = t as GDCTable;
|
||||||
|
return metadataTableDef.join() === (table as GDCTable).join();
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!trackedTable)
|
||||||
|
throw new Error('getTableRows: trackedTable not found in metadata');
|
||||||
|
|
||||||
|
const defaultQueryRoot = (table as GDCTable).join('_');
|
||||||
|
|
||||||
|
const { query, resultPath } = await generateGraphQLSelectQuery({
|
||||||
|
operationName: 'TableRows',
|
||||||
|
defaultQueryRoot,
|
||||||
|
columns,
|
||||||
|
tableCustomization: trackedTable.configuration,
|
||||||
|
sourceCustomization: source.customization,
|
||||||
|
options,
|
||||||
|
});
|
||||||
|
|
||||||
|
const graphqlResponse = await runGraphQL({
|
||||||
|
operationName: 'TableRows',
|
||||||
|
query,
|
||||||
|
httpClient,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = transformGraphqlResponse({
|
||||||
|
data: get(graphqlResponse.data, resultPath) ?? [],
|
||||||
|
tableCustomization: trackedTable.configuration,
|
||||||
|
sourceCustomization: source.customization,
|
||||||
|
columns,
|
||||||
|
});
|
||||||
|
|
||||||
|
return result;
|
||||||
|
};
|
1
console/src/features/DataSource/gdc/query/index.ts
Normal file
1
console/src/features/DataSource/gdc/query/index.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
export { getTableRows } from './getTableRows';
|
@ -6,6 +6,7 @@ import {
|
|||||||
getFKRelationships,
|
getFKRelationships,
|
||||||
getTablesListAsTree,
|
getTablesListAsTree,
|
||||||
} from './introspection';
|
} from './introspection';
|
||||||
|
import { getTableRows } from './query';
|
||||||
|
|
||||||
export type MssqlTable = { schema: string; name: string };
|
export type MssqlTable = { schema: string; name: string };
|
||||||
|
|
||||||
@ -49,4 +50,7 @@ export const mssql: Database = {
|
|||||||
getFKRelationships,
|
getFKRelationships,
|
||||||
getTablesListAsTree,
|
getTablesListAsTree,
|
||||||
},
|
},
|
||||||
|
query: {
|
||||||
|
getTableRows,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
60
console/src/features/DataSource/mssql/query/getTableRows.ts
Normal file
60
console/src/features/DataSource/mssql/query/getTableRows.ts
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
import { generateGraphQLSelectQuery } from '@/features/GraphQLUtils';
|
||||||
|
import get from 'lodash.get';
|
||||||
|
import { MssqlTable } from '..';
|
||||||
|
import { exportMetadata, runGraphQL } from '../../api';
|
||||||
|
import { transformGraphqlResponse } from '../../common/utils';
|
||||||
|
import { GetTableRowsProps, TableRow } from '../../types';
|
||||||
|
|
||||||
|
export const getTableRows = async ({
|
||||||
|
table,
|
||||||
|
dataSourceName,
|
||||||
|
httpClient,
|
||||||
|
columns,
|
||||||
|
options,
|
||||||
|
}: GetTableRowsProps): Promise<TableRow[]> => {
|
||||||
|
const { name, schema } = table as MssqlTable;
|
||||||
|
|
||||||
|
const source = (await exportMetadata({ httpClient })).metadata.sources.find(
|
||||||
|
({ name: sourceName }) => sourceName === dataSourceName
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If I can't find the source in the metadata, then there is something inconsistent on the server.
|
||||||
|
*/
|
||||||
|
if (!source) throw new Error('getTableRows: source not found in metadata');
|
||||||
|
|
||||||
|
// TODO: I think we can make it better, more generic if we relegate the table comparison thingy to a util function.
|
||||||
|
const trackedTable = source.tables.find(({ table: t }) => {
|
||||||
|
const metadataTableDef = t as MssqlTable;
|
||||||
|
return metadataTableDef.name === name && metadataTableDef.schema === schema;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!trackedTable)
|
||||||
|
throw new Error('getTableRows: trackedTable not found in metadata');
|
||||||
|
|
||||||
|
const defaultQueryRoot = schema === 'dbo' ? name : `${schema}_${name}`;
|
||||||
|
|
||||||
|
const { query, resultPath } = await generateGraphQLSelectQuery({
|
||||||
|
operationName: 'TableRows',
|
||||||
|
defaultQueryRoot,
|
||||||
|
columns,
|
||||||
|
tableCustomization: trackedTable.configuration,
|
||||||
|
sourceCustomization: source.customization,
|
||||||
|
options,
|
||||||
|
});
|
||||||
|
|
||||||
|
const graphqlResponse = await runGraphQL({
|
||||||
|
operationName: 'TableRows',
|
||||||
|
query,
|
||||||
|
httpClient,
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = transformGraphqlResponse({
|
||||||
|
data: get(graphqlResponse.data, resultPath) ?? [],
|
||||||
|
tableCustomization: trackedTable.configuration,
|
||||||
|
sourceCustomization: source.customization,
|
||||||
|
columns,
|
||||||
|
});
|
||||||
|
|
||||||
|
return result;
|
||||||
|
};
|
1
console/src/features/DataSource/mssql/query/index.ts
Normal file
1
console/src/features/DataSource/mssql/query/index.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
export { getTableRows } from './getTableRows';
|
@ -18,7 +18,7 @@ export const getTableRows = async (props: GetTableRowsProps) => {
|
|||||||
source: dataSourceName,
|
source: dataSourceName,
|
||||||
table,
|
table,
|
||||||
columns,
|
columns,
|
||||||
where: options?.where,
|
where: options?.where ? { $and: options.where } : undefined,
|
||||||
offset: options?.offset,
|
offset: options?.offset,
|
||||||
limit: options?.limit,
|
limit: options?.limit,
|
||||||
order_by: options?.order_by,
|
order_by: options?.order_by,
|
||||||
|
@ -85,24 +85,13 @@ export type GetTableRowsProps = {
|
|||||||
} & NetworkArgs;
|
} & NetworkArgs;
|
||||||
export type TableRow = Record<string, unknown>;
|
export type TableRow = Record<string, unknown>;
|
||||||
|
|
||||||
export type validOperators =
|
export type validOperators = string;
|
||||||
| '$eq'
|
|
||||||
| '$ne'
|
|
||||||
| '$in'
|
|
||||||
| '$nin'
|
|
||||||
| '$gt'
|
|
||||||
| '$lt'
|
|
||||||
| '$gte'
|
|
||||||
| '$lte';
|
|
||||||
|
|
||||||
export type AndExp = Record<'$and', BoolExp[]>;
|
|
||||||
export type OrExp = Record<'$or', BoolExp[]>;
|
|
||||||
export type NotExp = Record<'$not', BoolExp[]>;
|
|
||||||
export type ColumnExpValue = Record<validOperators | string, any>;
|
|
||||||
export type ColumnExp = Record<string, ColumnExpValue>;
|
|
||||||
export type BoolExp = AndExp | OrExp | NotExp | ColumnExp;
|
|
||||||
export type SelectColumn = string | { name: string; columns: SelectColumn[] };
|
export type SelectColumn = string | { name: string; columns: SelectColumn[] };
|
||||||
export type WhereClause = BoolExp | Record<string, any>;
|
export type WhereClause = Record<
|
||||||
|
validOperators,
|
||||||
|
Record<string, string | number | boolean>
|
||||||
|
>[];
|
||||||
export type OrderByType = 'asc' | 'desc';
|
export type OrderByType = 'asc' | 'desc';
|
||||||
export type OrderByNulls = 'first' | 'last';
|
export type OrderByNulls = 'first' | 'last';
|
||||||
export type OrderBy = {
|
export type OrderBy = {
|
||||||
|
1
console/src/features/GraphQLUtils/index.ts
Normal file
1
console/src/features/GraphQLUtils/index.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
export * from './query';
|
@ -0,0 +1,62 @@
|
|||||||
|
import { MetadataTable, Source } from '@/features/MetadataAPI';
|
||||||
|
import { getMutationRoot } from './getMutationRoot';
|
||||||
|
|
||||||
|
export const generateGraphQLMutation = async ({
|
||||||
|
defaultQueryRoot,
|
||||||
|
tableCustomization,
|
||||||
|
sourceCustomization,
|
||||||
|
objects,
|
||||||
|
operationName,
|
||||||
|
}: {
|
||||||
|
operationName?: string;
|
||||||
|
defaultQueryRoot: string;
|
||||||
|
tableCustomization: MetadataTable['configuration'];
|
||||||
|
sourceCustomization: Source['customization'];
|
||||||
|
objects: Record<string, string | number | boolean>;
|
||||||
|
}) => {
|
||||||
|
const queryRoot = getMutationRoot({
|
||||||
|
defaultQueryRoot,
|
||||||
|
operation: 'insert',
|
||||||
|
/**
|
||||||
|
* Configuration contains the custom names for the following -
|
||||||
|
* 1. Table Name
|
||||||
|
* 2. Query roots - select, select_by_pk, select_aggregate
|
||||||
|
* 3. Column Names
|
||||||
|
*
|
||||||
|
* Custom names from metadata are user-provided values and will always assume priority in the final GQL schema
|
||||||
|
*/
|
||||||
|
configuration: tableCustomization,
|
||||||
|
sourceCustomization,
|
||||||
|
});
|
||||||
|
|
||||||
|
const objectToInsert = Object.entries(objects).reduce<string>((acc, x) => {
|
||||||
|
const [column, value] = x;
|
||||||
|
return `${column}: ${typeof value === 'string' ? `"${value}"` : value}`;
|
||||||
|
}, '');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If the source has a GQL namespace set for it, then we query for our `queryRoot` under that namespace
|
||||||
|
*/
|
||||||
|
if (sourceCustomization?.root_fields?.namespace)
|
||||||
|
return {
|
||||||
|
query: `mutation ${operationName ?? 'MyMutation'} {
|
||||||
|
${
|
||||||
|
sourceCustomization.root_fields.namespace
|
||||||
|
} (objects: { ${objectToInsert} }) {
|
||||||
|
${queryRoot} {
|
||||||
|
affected_rows
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}`,
|
||||||
|
resultPath: `${sourceCustomization.root_fields?.namespace}.${queryRoot}`,
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
query: `query ${operationName ?? 'MyQuery'} {
|
||||||
|
${queryRoot} (objects: { ${objectToInsert} }) {
|
||||||
|
affected_rows
|
||||||
|
}
|
||||||
|
}`,
|
||||||
|
resultPath: queryRoot,
|
||||||
|
};
|
||||||
|
};
|
@ -0,0 +1,60 @@
|
|||||||
|
import { MetadataTable, Source } from '@/features/MetadataAPI';
|
||||||
|
|
||||||
|
export type AllowedMutationOperation =
|
||||||
|
| 'insert'
|
||||||
|
| 'insert_one'
|
||||||
|
| 'update'
|
||||||
|
| 'update_by_pk'
|
||||||
|
| 'delete'
|
||||||
|
| 'delete_by_pk';
|
||||||
|
|
||||||
|
export const getMutationRoot = ({
|
||||||
|
defaultQueryRoot,
|
||||||
|
configuration,
|
||||||
|
operation,
|
||||||
|
sourceCustomization,
|
||||||
|
}: {
|
||||||
|
defaultQueryRoot: string;
|
||||||
|
configuration?: MetadataTable['configuration'];
|
||||||
|
operation: AllowedMutationOperation;
|
||||||
|
sourceCustomization?: Source['customization'];
|
||||||
|
defaultSchema?: string;
|
||||||
|
}): string => {
|
||||||
|
/**
|
||||||
|
* Priority 1: Check if `operation` has a custom name. If so, use that for the query root.
|
||||||
|
* Also there is no need to suffix operation names to the name here, since you're replacing the entire query root name
|
||||||
|
* and can uniquely identify an operation query
|
||||||
|
*/
|
||||||
|
const customRootName = configuration?.custom_root_fields?.[operation];
|
||||||
|
if (customRootName)
|
||||||
|
return `${sourceCustomization?.root_fields?.prefix ?? ''}${customRootName}${
|
||||||
|
sourceCustomization?.root_fields?.suffix ?? ''
|
||||||
|
}`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Priority 2: Check if the table has a custom name set. If so, use that for query root.
|
||||||
|
* (OR)
|
||||||
|
* Default: Just use the table name itself as the query root.
|
||||||
|
* Note: Postgres's `public` schema tables' query roots are not prefixed with the schema name in the final
|
||||||
|
* generated GraphQL schema.
|
||||||
|
*/
|
||||||
|
let baseQueryRoot = defaultQueryRoot;
|
||||||
|
|
||||||
|
if (configuration?.custom_name) baseQueryRoot = configuration?.custom_name;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* for `select_by_pk` and `select_aggregate` the following suffixes are required if there is no custom field name set
|
||||||
|
*/
|
||||||
|
if (operation === 'insert_one') baseQueryRoot = `${baseQueryRoot}_one`;
|
||||||
|
|
||||||
|
if (operation === 'update_by_pk' || operation === 'delete_by_pk')
|
||||||
|
baseQueryRoot = `${baseQueryRoot}_by_pk`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The `select` operation has no operation suffix.
|
||||||
|
* `sourceCustomization` is independent of the table level GQL customization - prefix/suffix are to be added to the `queryRoot` finally.
|
||||||
|
*/
|
||||||
|
return `${sourceCustomization?.root_fields?.prefix ?? ''}${baseQueryRoot}${
|
||||||
|
sourceCustomization?.root_fields?.suffix ?? ''
|
||||||
|
}`;
|
||||||
|
};
|
@ -0,0 +1,433 @@
|
|||||||
|
import { MetadataTable, Source } from '../../../../MetadataAPI';
|
||||||
|
import { generateGraphQLSelectQuery } from './generateGraphQLSelectQuery';
|
||||||
|
|
||||||
|
describe('GraphQL utils for browse rows - ', () => {
|
||||||
|
describe('[select] a table with no customization', () => {
|
||||||
|
it('Generates correct GraphQL query', async () => {
|
||||||
|
const { query } = await generateGraphQLSelectQuery({
|
||||||
|
defaultQueryRoot: 'sales_stores',
|
||||||
|
columns: [
|
||||||
|
'store_id',
|
||||||
|
'store_name',
|
||||||
|
'phone',
|
||||||
|
'email',
|
||||||
|
'street',
|
||||||
|
'city',
|
||||||
|
'state',
|
||||||
|
'zip_code',
|
||||||
|
],
|
||||||
|
tableCustomization: undefined,
|
||||||
|
sourceCustomization: undefined,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(query).toMatchInlineSnapshot(`
|
||||||
|
"query MyQuery {
|
||||||
|
sales_stores {
|
||||||
|
store_id
|
||||||
|
,store_name
|
||||||
|
,phone
|
||||||
|
,email
|
||||||
|
,street
|
||||||
|
,city
|
||||||
|
,state
|
||||||
|
,zip_code
|
||||||
|
|
||||||
|
}
|
||||||
|
}"
|
||||||
|
`);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('[select] a table with table name customization', () => {
|
||||||
|
it('Generates correct GraphQL query', async () => {
|
||||||
|
const tableCustomization: MetadataTable['configuration'] = {
|
||||||
|
column_config: {},
|
||||||
|
custom_column_names: {},
|
||||||
|
custom_name: 'CustomNameForTable',
|
||||||
|
custom_root_fields: {},
|
||||||
|
};
|
||||||
|
|
||||||
|
const { query } = await generateGraphQLSelectQuery({
|
||||||
|
defaultQueryRoot: 'sales_stores',
|
||||||
|
columns: [
|
||||||
|
'store_id',
|
||||||
|
'store_name',
|
||||||
|
'phone',
|
||||||
|
'email',
|
||||||
|
'street',
|
||||||
|
'city',
|
||||||
|
'state',
|
||||||
|
'zip_code',
|
||||||
|
],
|
||||||
|
tableCustomization,
|
||||||
|
sourceCustomization: undefined,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(query).toMatchInlineSnapshot(`
|
||||||
|
"query MyQuery {
|
||||||
|
CustomNameForTable {
|
||||||
|
store_id
|
||||||
|
,store_name
|
||||||
|
,phone
|
||||||
|
,email
|
||||||
|
,street
|
||||||
|
,city
|
||||||
|
,state
|
||||||
|
,zip_code
|
||||||
|
|
||||||
|
}
|
||||||
|
}"
|
||||||
|
`);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('[select] a table with select query customization', () => {
|
||||||
|
it('Generates correct GraphQL query', async () => {
|
||||||
|
const tableCustomization: MetadataTable['configuration'] = {
|
||||||
|
column_config: {},
|
||||||
|
custom_column_names: {},
|
||||||
|
custom_root_fields: { select: 'CustomSelectQueryName' },
|
||||||
|
};
|
||||||
|
const { query } = await generateGraphQLSelectQuery({
|
||||||
|
defaultQueryRoot: 'sales_stores',
|
||||||
|
columns: [
|
||||||
|
'store_id',
|
||||||
|
'store_name',
|
||||||
|
'phone',
|
||||||
|
'email',
|
||||||
|
'street',
|
||||||
|
'city',
|
||||||
|
'state',
|
||||||
|
'zip_code',
|
||||||
|
],
|
||||||
|
tableCustomization,
|
||||||
|
sourceCustomization: {},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(query).toMatchInlineSnapshot(`
|
||||||
|
"query MyQuery {
|
||||||
|
CustomSelectQueryName {
|
||||||
|
store_id
|
||||||
|
,store_name
|
||||||
|
,phone
|
||||||
|
,email
|
||||||
|
,street
|
||||||
|
,city
|
||||||
|
,state
|
||||||
|
,zip_code
|
||||||
|
|
||||||
|
}
|
||||||
|
}"
|
||||||
|
`);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('[select] a table with custom field names', () => {
|
||||||
|
it('Generates correct GraphQL query', async () => {
|
||||||
|
const tableCustomization: MetadataTable['configuration'] = {
|
||||||
|
column_config: {
|
||||||
|
phone: {
|
||||||
|
custom_name: 'customNameForPhone',
|
||||||
|
},
|
||||||
|
email: {
|
||||||
|
custom_name: 'customNameForEmail',
|
||||||
|
},
|
||||||
|
street: {
|
||||||
|
custom_name: 'customNameForStreet',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
custom_column_names: {
|
||||||
|
phone: 'customNameForPhone',
|
||||||
|
email: 'customNameForEmail',
|
||||||
|
street: 'customNameForStreet',
|
||||||
|
},
|
||||||
|
custom_root_fields: {},
|
||||||
|
};
|
||||||
|
const { query } = await generateGraphQLSelectQuery({
|
||||||
|
defaultQueryRoot: 'sales_stores',
|
||||||
|
columns: [
|
||||||
|
'store_id',
|
||||||
|
'store_name',
|
||||||
|
'phone',
|
||||||
|
'email',
|
||||||
|
'street',
|
||||||
|
'city',
|
||||||
|
'state',
|
||||||
|
'zip_code',
|
||||||
|
],
|
||||||
|
tableCustomization,
|
||||||
|
sourceCustomization: {},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(query).toMatchInlineSnapshot(`
|
||||||
|
"query MyQuery {
|
||||||
|
sales_stores {
|
||||||
|
store_id
|
||||||
|
,store_name
|
||||||
|
,customNameForPhone
|
||||||
|
,customNameForEmail
|
||||||
|
,customNameForStreet
|
||||||
|
,city
|
||||||
|
,state
|
||||||
|
,zip_code
|
||||||
|
|
||||||
|
}
|
||||||
|
}"
|
||||||
|
`);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('[select] a table with source level customization (namespace, prefix & suffix)', () => {
|
||||||
|
it('Generates correct GraphQL query', async () => {
|
||||||
|
const sourceCustomization: Source['customization'] = {
|
||||||
|
root_fields: {
|
||||||
|
namespace: 'SourceNamespace_',
|
||||||
|
prefix: 'TablePrefix_',
|
||||||
|
suffix: '_TableSuffix',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const { query } = await generateGraphQLSelectQuery({
|
||||||
|
defaultQueryRoot: 'sales_stores',
|
||||||
|
columns: [
|
||||||
|
'store_id',
|
||||||
|
'store_name',
|
||||||
|
'phone',
|
||||||
|
'email',
|
||||||
|
'street',
|
||||||
|
'city',
|
||||||
|
'state',
|
||||||
|
'zip_code',
|
||||||
|
],
|
||||||
|
tableCustomization: {},
|
||||||
|
sourceCustomization,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(query).toMatchInlineSnapshot(`
|
||||||
|
"query MyQuery {
|
||||||
|
SourceNamespace_ {
|
||||||
|
TablePrefix_sales_stores_TableSuffix {
|
||||||
|
store_id
|
||||||
|
,store_name
|
||||||
|
,phone
|
||||||
|
,email
|
||||||
|
,street
|
||||||
|
,city
|
||||||
|
,state
|
||||||
|
,zip_code
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}"
|
||||||
|
`);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('[select] a table with all possible customizations at table, source (namespace, prefix & suffix) & column level (no custom query root)', () => {
|
||||||
|
it('Generates correct GraphQL query', async () => {
|
||||||
|
const tableCustomization: MetadataTable['configuration'] = {
|
||||||
|
column_config: {
|
||||||
|
phone: {
|
||||||
|
custom_name: 'customNameForPhone',
|
||||||
|
},
|
||||||
|
email: {
|
||||||
|
custom_name: 'customNameForEmail',
|
||||||
|
},
|
||||||
|
street: {
|
||||||
|
custom_name: 'customNameForStreet',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
custom_column_names: {
|
||||||
|
phone: 'customNameForPhone',
|
||||||
|
email: 'customNameForEmail',
|
||||||
|
street: 'customNameForStreet',
|
||||||
|
},
|
||||||
|
custom_name: 'CustomNameForTable',
|
||||||
|
custom_root_fields: {},
|
||||||
|
};
|
||||||
|
|
||||||
|
const sourceCustomization: Source['customization'] = {
|
||||||
|
root_fields: {
|
||||||
|
namespace: 'SourceNamespace_',
|
||||||
|
prefix: 'TablePrefix_',
|
||||||
|
suffix: '_TableSuffix',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const { query } = await generateGraphQLSelectQuery({
|
||||||
|
defaultQueryRoot: 'sales_stores',
|
||||||
|
columns: [
|
||||||
|
'store_id',
|
||||||
|
'store_name',
|
||||||
|
'phone',
|
||||||
|
'email',
|
||||||
|
'street',
|
||||||
|
'city',
|
||||||
|
'state',
|
||||||
|
'zip_code',
|
||||||
|
],
|
||||||
|
tableCustomization,
|
||||||
|
sourceCustomization,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(query).toMatchInlineSnapshot(`
|
||||||
|
"query MyQuery {
|
||||||
|
SourceNamespace_ {
|
||||||
|
TablePrefix_CustomNameForTable_TableSuffix {
|
||||||
|
store_id
|
||||||
|
,store_name
|
||||||
|
,customNameForPhone
|
||||||
|
,customNameForEmail
|
||||||
|
,customNameForStreet
|
||||||
|
,city
|
||||||
|
,state
|
||||||
|
,zip_code
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}"
|
||||||
|
`);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('[select] a table with all possible customizations at table, source (namespace, prefix & suffix) & column level (with custom query root)', () => {
|
||||||
|
it('Generates correct GraphQL query', async () => {
|
||||||
|
const tableCustomization: MetadataTable['configuration'] = {
|
||||||
|
column_config: {
|
||||||
|
phone: {
|
||||||
|
custom_name: 'customNameForPhone',
|
||||||
|
},
|
||||||
|
email: {
|
||||||
|
custom_name: 'customNameForEmail',
|
||||||
|
},
|
||||||
|
street: {
|
||||||
|
custom_name: 'customNameForStreet',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
custom_column_names: {
|
||||||
|
phone: 'customNameForPhone',
|
||||||
|
email: 'customNameForEmail',
|
||||||
|
street: 'customNameForStreet',
|
||||||
|
},
|
||||||
|
custom_name: 'CustomNameForTable',
|
||||||
|
custom_root_fields: { select: 'CustomSelectQueryName' },
|
||||||
|
};
|
||||||
|
|
||||||
|
const sourceCustomization: Source['customization'] = {
|
||||||
|
root_fields: {
|
||||||
|
namespace: 'SourceNamespace_',
|
||||||
|
prefix: 'TablePrefix_',
|
||||||
|
suffix: '_TableSuffix',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const { query } = await generateGraphQLSelectQuery({
|
||||||
|
defaultQueryRoot: 'sales_stores',
|
||||||
|
columns: [
|
||||||
|
'store_id',
|
||||||
|
'store_name',
|
||||||
|
'phone',
|
||||||
|
'email',
|
||||||
|
'street',
|
||||||
|
'city',
|
||||||
|
'state',
|
||||||
|
'zip_code',
|
||||||
|
],
|
||||||
|
tableCustomization,
|
||||||
|
sourceCustomization,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(query).toMatchInlineSnapshot(`
|
||||||
|
"query MyQuery {
|
||||||
|
SourceNamespace_ {
|
||||||
|
TablePrefix_CustomSelectQueryName_TableSuffix {
|
||||||
|
store_id
|
||||||
|
,store_name
|
||||||
|
,customNameForPhone
|
||||||
|
,customNameForEmail
|
||||||
|
,customNameForStreet
|
||||||
|
,city
|
||||||
|
,state
|
||||||
|
,zip_code
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}"
|
||||||
|
`);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('[select] a table with source & table level customzations + options', () => {
|
||||||
|
it('Generates correct GraphQL query', async () => {
|
||||||
|
const tableCustomization: MetadataTable['configuration'] = {
|
||||||
|
column_config: {
|
||||||
|
phone: {
|
||||||
|
custom_name: 'customNameForPhone',
|
||||||
|
},
|
||||||
|
email: {
|
||||||
|
custom_name: 'customNameForEmail',
|
||||||
|
},
|
||||||
|
street: {
|
||||||
|
custom_name: 'customNameForStreet',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
custom_column_names: {
|
||||||
|
phone: 'customNameForPhone',
|
||||||
|
email: 'customNameForEmail',
|
||||||
|
street: 'customNameForStreet',
|
||||||
|
},
|
||||||
|
custom_name: 'CustomNameForTable',
|
||||||
|
custom_root_fields: { select: 'CustomSelectQueryName' },
|
||||||
|
};
|
||||||
|
|
||||||
|
const sourceCustomization: Source['customization'] = {
|
||||||
|
root_fields: {
|
||||||
|
namespace: 'SourceNamespace_',
|
||||||
|
prefix: 'TablePrefix_',
|
||||||
|
suffix: '_TableSuffix',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const { query } = await generateGraphQLSelectQuery({
|
||||||
|
defaultQueryRoot: 'sales_stores',
|
||||||
|
columns: [
|
||||||
|
'store_id',
|
||||||
|
'store_name',
|
||||||
|
'phone',
|
||||||
|
'email',
|
||||||
|
'street',
|
||||||
|
'city',
|
||||||
|
'state',
|
||||||
|
'zip_code',
|
||||||
|
],
|
||||||
|
tableCustomization,
|
||||||
|
sourceCustomization,
|
||||||
|
options: {
|
||||||
|
limit: 10,
|
||||||
|
where: [
|
||||||
|
{ store_id: { _eq: 4 } },
|
||||||
|
{ street: { _eq: 'some street name' } },
|
||||||
|
],
|
||||||
|
order_by: [{ column: 'street', type: 'desc' }],
|
||||||
|
offset: 15,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(query).toMatchInlineSnapshot(`
|
||||||
|
"query MyQuery {
|
||||||
|
SourceNamespace_ (where: {store_id: { _eq: 4},customNameForStreet: { _eq: \\"some street name\\"}},order_by: {customNameForStreet: desc},limit: 10,offset: 15) {
|
||||||
|
TablePrefix_CustomSelectQueryName_TableSuffix {
|
||||||
|
store_id
|
||||||
|
,store_name
|
||||||
|
,customNameForPhone
|
||||||
|
,customNameForEmail
|
||||||
|
,customNameForStreet
|
||||||
|
,city
|
||||||
|
,state
|
||||||
|
,zip_code
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}"
|
||||||
|
`);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
@ -0,0 +1,92 @@
|
|||||||
|
import { MetadataTable, Source } from '@/features/MetadataAPI';
|
||||||
|
import { OrderBy, WhereClause } from '../../../types';
|
||||||
|
import {
|
||||||
|
getFields,
|
||||||
|
getLimitClause,
|
||||||
|
getOffsetClause,
|
||||||
|
getOrderByClauses,
|
||||||
|
getWhereClauses,
|
||||||
|
} from '../../../utils';
|
||||||
|
import { getQueryRoot } from '../../getQueryRoot';
|
||||||
|
|
||||||
|
export const generateGraphQLSelectQuery = async ({
|
||||||
|
defaultQueryRoot,
|
||||||
|
columns,
|
||||||
|
tableCustomization,
|
||||||
|
sourceCustomization,
|
||||||
|
options,
|
||||||
|
operationName,
|
||||||
|
}: {
|
||||||
|
operationName?: string;
|
||||||
|
defaultQueryRoot: string;
|
||||||
|
columns: string[];
|
||||||
|
tableCustomization: MetadataTable['configuration'];
|
||||||
|
sourceCustomization: Source['customization'];
|
||||||
|
options?: {
|
||||||
|
where?: WhereClause;
|
||||||
|
offset?: number;
|
||||||
|
limit?: number;
|
||||||
|
order_by?: OrderBy[];
|
||||||
|
};
|
||||||
|
}) => {
|
||||||
|
const queryRoot = getQueryRoot({
|
||||||
|
defaultQueryRoot,
|
||||||
|
operation: 'select',
|
||||||
|
/**
|
||||||
|
* Configuration contains the custom names for the following -
|
||||||
|
* 1. Table Name
|
||||||
|
* 2. Query roots - select, select_by_pk, select_aggregate
|
||||||
|
* 3. Column Names
|
||||||
|
*
|
||||||
|
* Custom names from metadata are user-provided values and will always assume priority in the final GQL schema
|
||||||
|
*/
|
||||||
|
configuration: tableCustomization,
|
||||||
|
sourceCustomization,
|
||||||
|
});
|
||||||
|
|
||||||
|
const fields = getFields({
|
||||||
|
columns,
|
||||||
|
configuration: tableCustomization,
|
||||||
|
});
|
||||||
|
|
||||||
|
const whereClauses = getWhereClauses({
|
||||||
|
whereClause: options?.where,
|
||||||
|
tableCustomization,
|
||||||
|
});
|
||||||
|
const orderByClauses = getOrderByClauses({
|
||||||
|
orderByClauses: options?.order_by,
|
||||||
|
tableCustomization,
|
||||||
|
});
|
||||||
|
const limitClause = getLimitClause(options?.limit);
|
||||||
|
const offsetClause = getOffsetClause(options?.offset);
|
||||||
|
|
||||||
|
const clauses = [whereClauses, orderByClauses, limitClause, offsetClause]
|
||||||
|
.filter(clause => clause.length)
|
||||||
|
.join(',');
|
||||||
|
|
||||||
|
const mergedClauses = clauses.length ? `(${clauses})` : '';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If the source has a GQL namespace set for it, then we query for our `queryRoot` under that namespace
|
||||||
|
*/
|
||||||
|
if (sourceCustomization?.root_fields?.namespace)
|
||||||
|
return {
|
||||||
|
query: `query ${operationName ?? 'MyQuery'} {
|
||||||
|
${sourceCustomization.root_fields.namespace} ${mergedClauses} {
|
||||||
|
${queryRoot} {
|
||||||
|
${fields.map(field => `${field} \n`)}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}`,
|
||||||
|
resultPath: `${sourceCustomization.root_fields?.namespace}.${queryRoot}`,
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
query: `query ${operationName ?? 'MyQuery'} {
|
||||||
|
${queryRoot} ${mergedClauses} {
|
||||||
|
${fields.map(field => `${field} \n`)}
|
||||||
|
}
|
||||||
|
}`,
|
||||||
|
resultPath: queryRoot,
|
||||||
|
};
|
||||||
|
};
|
@ -0,0 +1 @@
|
|||||||
|
export * from './generateGraphQLSelectQuery';
|
@ -0,0 +1 @@
|
|||||||
|
export * from './generateGraphQLSelectQuery';
|
56
console/src/features/GraphQLUtils/query/getQueryRoot.ts
Normal file
56
console/src/features/GraphQLUtils/query/getQueryRoot.ts
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
import { MetadataTable, Source } from '@/features/MetadataAPI';
|
||||||
|
|
||||||
|
export type AllowedQueryOperation =
|
||||||
|
| 'select'
|
||||||
|
| 'select_by_pk'
|
||||||
|
| 'select_aggregate';
|
||||||
|
export const getQueryRoot = ({
|
||||||
|
defaultQueryRoot,
|
||||||
|
configuration,
|
||||||
|
operation,
|
||||||
|
sourceCustomization,
|
||||||
|
}: {
|
||||||
|
defaultQueryRoot: string;
|
||||||
|
configuration?: MetadataTable['configuration'];
|
||||||
|
operation: AllowedQueryOperation;
|
||||||
|
sourceCustomization?: Source['customization'];
|
||||||
|
defaultSchema?: string;
|
||||||
|
}): string => {
|
||||||
|
/**
|
||||||
|
* Priority 1: Check if `operation` has a custom name. If so, use that for the query root.
|
||||||
|
* Also there is no need to suffix operation names to the name here, since you're replacing the entire query root name
|
||||||
|
* and can uniquely identify an operation query
|
||||||
|
*/
|
||||||
|
const customRootName = configuration?.custom_root_fields?.[operation];
|
||||||
|
if (customRootName)
|
||||||
|
return `${sourceCustomization?.root_fields?.prefix ?? ''}${customRootName}${
|
||||||
|
sourceCustomization?.root_fields?.suffix ?? ''
|
||||||
|
}`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Priority 2: Check if the table has a custom name set. If so, use that for query root.
|
||||||
|
* (OR)
|
||||||
|
* Default: Just use the table name itself as the query root.
|
||||||
|
* Note: Postgres's `public` schema tables' query roots are not prefixed with the schema name in the final
|
||||||
|
* generated GraphQL schema.
|
||||||
|
*/
|
||||||
|
let baseQueryRoot = defaultQueryRoot;
|
||||||
|
|
||||||
|
if (configuration?.custom_name) baseQueryRoot = configuration?.custom_name;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* for `select_by_pk` and `select_aggregate` the following suffixes are required if there is no custom field name set
|
||||||
|
*/
|
||||||
|
if (operation === 'select_by_pk') baseQueryRoot = `${baseQueryRoot}_by_pk`;
|
||||||
|
|
||||||
|
if (operation === 'select_aggregate')
|
||||||
|
baseQueryRoot = `${baseQueryRoot}_aggregate`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The `select` operation has no operation suffix.
|
||||||
|
* `sourceCustomization` is independent of the table level GQL customization - prefix/suffix are to be added to the `queryRoot` finally.
|
||||||
|
*/
|
||||||
|
return `${sourceCustomization?.root_fields?.prefix ?? ''}${baseQueryRoot}${
|
||||||
|
sourceCustomization?.root_fields?.suffix ?? ''
|
||||||
|
}`;
|
||||||
|
};
|
1
console/src/features/GraphQLUtils/query/index.ts
Normal file
1
console/src/features/GraphQLUtils/query/index.ts
Normal file
@ -0,0 +1 @@
|
|||||||
|
export * from './generateGraphQLQuery';
|
14
console/src/features/GraphQLUtils/types.ts
Normal file
14
console/src/features/GraphQLUtils/types.ts
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
export type validOperators = string;
|
||||||
|
|
||||||
|
export type WhereClause = Record<
|
||||||
|
validOperators,
|
||||||
|
Record<string, string | number | boolean>
|
||||||
|
>[];
|
||||||
|
|
||||||
|
export type OrderByType = 'asc' | 'desc';
|
||||||
|
export type OrderByNulls = 'first' | 'last';
|
||||||
|
export type OrderBy = {
|
||||||
|
column: string;
|
||||||
|
type: OrderByType;
|
||||||
|
nulls?: OrderByNulls;
|
||||||
|
};
|
96
console/src/features/GraphQLUtils/utils.ts
Normal file
96
console/src/features/GraphQLUtils/utils.ts
Normal file
@ -0,0 +1,96 @@
|
|||||||
|
import { MetadataTable } from '@/features/MetadataAPI';
|
||||||
|
import { OrderBy, WhereClause } from './types';
|
||||||
|
|
||||||
|
export const getFields = ({
|
||||||
|
columns,
|
||||||
|
configuration,
|
||||||
|
}: {
|
||||||
|
columns: string[];
|
||||||
|
configuration?: Record<string, any>;
|
||||||
|
}): string[] => {
|
||||||
|
return columns.map(column => {
|
||||||
|
const customColumnName = configuration?.custom_column_names?.[column];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* column names are the selection set used in the final GQL query.
|
||||||
|
* The actual column name from the table is used. But if a custom column name is already set by the user
|
||||||
|
* then, the custom name will assume the priority.
|
||||||
|
* Reference: https://hasura.io/docs/latest/api-reference/syntax-defs/#columnconfig
|
||||||
|
*/
|
||||||
|
|
||||||
|
if (customColumnName) return customColumnName;
|
||||||
|
|
||||||
|
return column;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getGraphQLColumnName = (
|
||||||
|
columnName: string,
|
||||||
|
tableCustomization: MetadataTable['configuration']
|
||||||
|
) => {
|
||||||
|
/**
|
||||||
|
* If there is a custom name for the column return that or stick to the actual one
|
||||||
|
*/
|
||||||
|
return (
|
||||||
|
tableCustomization?.column_config?.[columnName]?.custom_name ?? columnName
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getWhereClauses = ({
|
||||||
|
whereClause,
|
||||||
|
tableCustomization,
|
||||||
|
}: {
|
||||||
|
whereClause?: WhereClause;
|
||||||
|
tableCustomization?: MetadataTable['configuration'];
|
||||||
|
}): string => {
|
||||||
|
if (!whereClause) return '';
|
||||||
|
|
||||||
|
const expressions = whereClause.map(expression => {
|
||||||
|
const [columnName, columnExp] = Object.entries(expression)[0];
|
||||||
|
const [operator, value] = Object.entries(columnExp)[0];
|
||||||
|
|
||||||
|
const graphQLCompatibleColumnName = getGraphQLColumnName(
|
||||||
|
columnName,
|
||||||
|
tableCustomization
|
||||||
|
);
|
||||||
|
|
||||||
|
return `${graphQLCompatibleColumnName}: { ${operator}: ${
|
||||||
|
typeof value === 'string' ? `"${value}"` : value
|
||||||
|
}}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
return `where: {${expressions.join(',')}}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getOrderByClauses = ({
|
||||||
|
orderByClauses,
|
||||||
|
tableCustomization,
|
||||||
|
}: {
|
||||||
|
orderByClauses?: OrderBy[];
|
||||||
|
tableCustomization?: MetadataTable['configuration'];
|
||||||
|
}): string => {
|
||||||
|
if (!orderByClauses || !orderByClauses.length) return '';
|
||||||
|
|
||||||
|
const expressions = orderByClauses.map(expression => {
|
||||||
|
const graphQLCompatibleColumnName = getGraphQLColumnName(
|
||||||
|
expression.column,
|
||||||
|
tableCustomization
|
||||||
|
);
|
||||||
|
|
||||||
|
return `${graphQLCompatibleColumnName}: ${expression.type}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
return `order_by: {${expressions.join(',')}}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getLimitClause = (limit?: number) => {
|
||||||
|
if (!limit) return '';
|
||||||
|
|
||||||
|
return `limit: ${limit}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getOffsetClause = (offset?: number) => {
|
||||||
|
if (!offset) return '';
|
||||||
|
|
||||||
|
return `offset: ${offset}`;
|
||||||
|
};
|
@ -31,8 +31,12 @@ export type MetadataTableConfig = {
|
|||||||
delete?: string;
|
delete?: string;
|
||||||
delete_by_pk?: string;
|
delete_by_pk?: string;
|
||||||
};
|
};
|
||||||
column_config?: Record<string, { custom_name: string; comment: string }>;
|
column_config?: Record<string, { custom_name: string; comment?: string }>;
|
||||||
comment?: string;
|
comment?: string;
|
||||||
|
/**
|
||||||
|
* @deprecated do not use this anymore. Should be used only for backcompatiblity reasons
|
||||||
|
*/
|
||||||
|
custom_column_names?: Record<string, string>;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type MetadataTable = {
|
export type MetadataTable = {
|
||||||
|
@ -8,121 +8,121 @@
|
|||||||
* - Please do NOT serve this file on production.
|
* - Please do NOT serve this file on production.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const INTEGRITY_CHECKSUM = 'b3066ef78c2f9090b4ce87e874965995'
|
const INTEGRITY_CHECKSUM = 'b3066ef78c2f9090b4ce87e874965995';
|
||||||
const activeClientIds = new Set()
|
const activeClientIds = new Set();
|
||||||
|
|
||||||
self.addEventListener('install', function () {
|
self.addEventListener('install', function () {
|
||||||
self.skipWaiting()
|
self.skipWaiting();
|
||||||
})
|
});
|
||||||
|
|
||||||
self.addEventListener('activate', function (event) {
|
self.addEventListener('activate', function (event) {
|
||||||
event.waitUntil(self.clients.claim())
|
event.waitUntil(self.clients.claim());
|
||||||
})
|
});
|
||||||
|
|
||||||
self.addEventListener('message', async function (event) {
|
self.addEventListener('message', async function (event) {
|
||||||
const clientId = event.source.id
|
const clientId = event.source.id;
|
||||||
|
|
||||||
if (!clientId || !self.clients) {
|
if (!clientId || !self.clients) {
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const client = await self.clients.get(clientId)
|
const client = await self.clients.get(clientId);
|
||||||
|
|
||||||
if (!client) {
|
if (!client) {
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const allClients = await self.clients.matchAll({
|
const allClients = await self.clients.matchAll({
|
||||||
type: 'window',
|
type: 'window',
|
||||||
})
|
});
|
||||||
|
|
||||||
switch (event.data) {
|
switch (event.data) {
|
||||||
case 'KEEPALIVE_REQUEST': {
|
case 'KEEPALIVE_REQUEST': {
|
||||||
sendToClient(client, {
|
sendToClient(client, {
|
||||||
type: 'KEEPALIVE_RESPONSE',
|
type: 'KEEPALIVE_RESPONSE',
|
||||||
})
|
});
|
||||||
break
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case 'INTEGRITY_CHECK_REQUEST': {
|
case 'INTEGRITY_CHECK_REQUEST': {
|
||||||
sendToClient(client, {
|
sendToClient(client, {
|
||||||
type: 'INTEGRITY_CHECK_RESPONSE',
|
type: 'INTEGRITY_CHECK_RESPONSE',
|
||||||
payload: INTEGRITY_CHECKSUM,
|
payload: INTEGRITY_CHECKSUM,
|
||||||
})
|
});
|
||||||
break
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case 'MOCK_ACTIVATE': {
|
case 'MOCK_ACTIVATE': {
|
||||||
activeClientIds.add(clientId)
|
activeClientIds.add(clientId);
|
||||||
|
|
||||||
sendToClient(client, {
|
sendToClient(client, {
|
||||||
type: 'MOCKING_ENABLED',
|
type: 'MOCKING_ENABLED',
|
||||||
payload: true,
|
payload: true,
|
||||||
})
|
});
|
||||||
break
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case 'MOCK_DEACTIVATE': {
|
case 'MOCK_DEACTIVATE': {
|
||||||
activeClientIds.delete(clientId)
|
activeClientIds.delete(clientId);
|
||||||
break
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case 'CLIENT_CLOSED': {
|
case 'CLIENT_CLOSED': {
|
||||||
activeClientIds.delete(clientId)
|
activeClientIds.delete(clientId);
|
||||||
|
|
||||||
const remainingClients = allClients.filter((client) => {
|
const remainingClients = allClients.filter(client => {
|
||||||
return client.id !== clientId
|
return client.id !== clientId;
|
||||||
})
|
});
|
||||||
|
|
||||||
// Unregister itself when there are no more clients
|
// Unregister itself when there are no more clients
|
||||||
if (remainingClients.length === 0) {
|
if (remainingClients.length === 0) {
|
||||||
self.registration.unregister()
|
self.registration.unregister();
|
||||||
}
|
}
|
||||||
|
|
||||||
break
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
|
|
||||||
self.addEventListener('fetch', function (event) {
|
self.addEventListener('fetch', function (event) {
|
||||||
const { request } = event
|
const { request } = event;
|
||||||
const accept = request.headers.get('accept') || ''
|
const accept = request.headers.get('accept') || '';
|
||||||
|
|
||||||
// Bypass server-sent events.
|
// Bypass server-sent events.
|
||||||
if (accept.includes('text/event-stream')) {
|
if (accept.includes('text/event-stream')) {
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bypass navigation requests.
|
// Bypass navigation requests.
|
||||||
if (request.mode === 'navigate') {
|
if (request.mode === 'navigate') {
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Opening the DevTools triggers the "only-if-cached" request
|
// Opening the DevTools triggers the "only-if-cached" request
|
||||||
// that cannot be handled by the worker. Bypass such requests.
|
// that cannot be handled by the worker. Bypass such requests.
|
||||||
if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
|
if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bypass all requests when there are no active clients.
|
// Bypass all requests when there are no active clients.
|
||||||
// Prevents the self-unregistered worked from handling requests
|
// Prevents the self-unregistered worked from handling requests
|
||||||
// after it's been deleted (still remains active until the next reload).
|
// after it's been deleted (still remains active until the next reload).
|
||||||
if (activeClientIds.size === 0) {
|
if (activeClientIds.size === 0) {
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate unique request ID.
|
// Generate unique request ID.
|
||||||
const requestId = Math.random().toString(16).slice(2)
|
const requestId = Math.random().toString(16).slice(2);
|
||||||
|
|
||||||
event.respondWith(
|
event.respondWith(
|
||||||
handleRequest(event, requestId).catch((error) => {
|
handleRequest(event, requestId).catch(error => {
|
||||||
if (error.name === 'NetworkError') {
|
if (error.name === 'NetworkError') {
|
||||||
console.warn(
|
console.warn(
|
||||||
'[MSW] Successfully emulated a network error for the "%s %s" request.',
|
'[MSW] Successfully emulated a network error for the "%s %s" request.',
|
||||||
request.method,
|
request.method,
|
||||||
request.url,
|
request.url
|
||||||
)
|
);
|
||||||
return
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// At this point, any exception indicates an issue with the original request/response.
|
// At this point, any exception indicates an issue with the original request/response.
|
||||||
@ -131,22 +131,22 @@ self.addEventListener('fetch', function (event) {
|
|||||||
[MSW] Caught an exception from the "%s %s" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,
|
[MSW] Caught an exception from the "%s %s" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,
|
||||||
request.method,
|
request.method,
|
||||||
request.url,
|
request.url,
|
||||||
`${error.name}: ${error.message}`,
|
`${error.name}: ${error.message}`
|
||||||
)
|
);
|
||||||
}),
|
})
|
||||||
)
|
);
|
||||||
})
|
});
|
||||||
|
|
||||||
async function handleRequest(event, requestId) {
|
async function handleRequest(event, requestId) {
|
||||||
const client = await resolveMainClient(event)
|
const client = await resolveMainClient(event);
|
||||||
const response = await getResponse(event, client, requestId)
|
const response = await getResponse(event, client, requestId);
|
||||||
|
|
||||||
// Send back the response clone for the "response:*" life-cycle events.
|
// Send back the response clone for the "response:*" life-cycle events.
|
||||||
// Ensure MSW is active and ready to handle the message, otherwise
|
// Ensure MSW is active and ready to handle the message, otherwise
|
||||||
// this message will pend indefinitely.
|
// this message will pend indefinitely.
|
||||||
if (client && activeClientIds.has(client.id)) {
|
if (client && activeClientIds.has(client.id)) {
|
||||||
;(async function () {
|
(async function () {
|
||||||
const clonedResponse = response.clone()
|
const clonedResponse = response.clone();
|
||||||
sendToClient(client, {
|
sendToClient(client, {
|
||||||
type: 'RESPONSE',
|
type: 'RESPONSE',
|
||||||
payload: {
|
payload: {
|
||||||
@ -160,11 +160,11 @@ async function handleRequest(event, requestId) {
|
|||||||
headers: Object.fromEntries(clonedResponse.headers.entries()),
|
headers: Object.fromEntries(clonedResponse.headers.entries()),
|
||||||
redirected: clonedResponse.redirected,
|
redirected: clonedResponse.redirected,
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
})()
|
})();
|
||||||
}
|
}
|
||||||
|
|
||||||
return response
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Resolve the main client for the given event.
|
// Resolve the main client for the given event.
|
||||||
@ -172,49 +172,49 @@ async function handleRequest(event, requestId) {
|
|||||||
// that registered the worker. It's with the latter the worker should
|
// that registered the worker. It's with the latter the worker should
|
||||||
// communicate with during the response resolving phase.
|
// communicate with during the response resolving phase.
|
||||||
async function resolveMainClient(event) {
|
async function resolveMainClient(event) {
|
||||||
const client = await self.clients.get(event.clientId)
|
const client = await self.clients.get(event.clientId);
|
||||||
|
|
||||||
if (client.frameType === 'top-level') {
|
if (client.frameType === 'top-level') {
|
||||||
return client
|
return client;
|
||||||
}
|
}
|
||||||
|
|
||||||
const allClients = await self.clients.matchAll({
|
const allClients = await self.clients.matchAll({
|
||||||
type: 'window',
|
type: 'window',
|
||||||
})
|
});
|
||||||
|
|
||||||
return allClients
|
return allClients
|
||||||
.filter((client) => {
|
.filter(client => {
|
||||||
// Get only those clients that are currently visible.
|
// Get only those clients that are currently visible.
|
||||||
return client.visibilityState === 'visible'
|
return client.visibilityState === 'visible';
|
||||||
})
|
})
|
||||||
.find((client) => {
|
.find(client => {
|
||||||
// Find the client ID that's recorded in the
|
// Find the client ID that's recorded in the
|
||||||
// set of clients that have registered the worker.
|
// set of clients that have registered the worker.
|
||||||
return activeClientIds.has(client.id)
|
return activeClientIds.has(client.id);
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getResponse(event, client, requestId) {
|
async function getResponse(event, client, requestId) {
|
||||||
const { request } = event
|
const { request } = event;
|
||||||
const clonedRequest = request.clone()
|
const clonedRequest = request.clone();
|
||||||
|
|
||||||
function passthrough() {
|
function passthrough() {
|
||||||
// Clone the request because it might've been already used
|
// Clone the request because it might've been already used
|
||||||
// (i.e. its body has been read and sent to the client).
|
// (i.e. its body has been read and sent to the client).
|
||||||
const headers = Object.fromEntries(clonedRequest.headers.entries())
|
const headers = Object.fromEntries(clonedRequest.headers.entries());
|
||||||
|
|
||||||
// Remove MSW-specific request headers so the bypassed requests
|
// Remove MSW-specific request headers so the bypassed requests
|
||||||
// comply with the server's CORS preflight check.
|
// comply with the server's CORS preflight check.
|
||||||
// Operate with the headers as an object because request "Headers"
|
// Operate with the headers as an object because request "Headers"
|
||||||
// are immutable.
|
// are immutable.
|
||||||
delete headers['x-msw-bypass']
|
delete headers['x-msw-bypass'];
|
||||||
|
|
||||||
return fetch(clonedRequest, { headers })
|
return fetch(clonedRequest, { headers });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bypass mocking when the client is not active.
|
// Bypass mocking when the client is not active.
|
||||||
if (!client) {
|
if (!client) {
|
||||||
return passthrough()
|
return passthrough();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bypass initial page load requests (i.e. static assets).
|
// Bypass initial page load requests (i.e. static assets).
|
||||||
@ -222,13 +222,13 @@ async function getResponse(event, client, requestId) {
|
|||||||
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
|
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
|
||||||
// and is not ready to handle requests.
|
// and is not ready to handle requests.
|
||||||
if (!activeClientIds.has(client.id)) {
|
if (!activeClientIds.has(client.id)) {
|
||||||
return passthrough()
|
return passthrough();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bypass requests with the explicit bypass header.
|
// Bypass requests with the explicit bypass header.
|
||||||
// Such requests can be issued by "ctx.fetch()".
|
// Such requests can be issued by "ctx.fetch()".
|
||||||
if (request.headers.get('x-msw-bypass') === 'true') {
|
if (request.headers.get('x-msw-bypass') === 'true') {
|
||||||
return passthrough()
|
return passthrough();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Notify the client that a request has been intercepted.
|
// Notify the client that a request has been intercepted.
|
||||||
@ -251,53 +251,53 @@ async function getResponse(event, client, requestId) {
|
|||||||
bodyUsed: request.bodyUsed,
|
bodyUsed: request.bodyUsed,
|
||||||
keepalive: request.keepalive,
|
keepalive: request.keepalive,
|
||||||
},
|
},
|
||||||
})
|
});
|
||||||
|
|
||||||
switch (clientMessage.type) {
|
switch (clientMessage.type) {
|
||||||
case 'MOCK_RESPONSE': {
|
case 'MOCK_RESPONSE': {
|
||||||
return respondWithMock(clientMessage.data)
|
return respondWithMock(clientMessage.data);
|
||||||
}
|
}
|
||||||
|
|
||||||
case 'MOCK_NOT_FOUND': {
|
case 'MOCK_NOT_FOUND': {
|
||||||
return passthrough()
|
return passthrough();
|
||||||
}
|
}
|
||||||
|
|
||||||
case 'NETWORK_ERROR': {
|
case 'NETWORK_ERROR': {
|
||||||
const { name, message } = clientMessage.data
|
const { name, message } = clientMessage.data;
|
||||||
const networkError = new Error(message)
|
const networkError = new Error(message);
|
||||||
networkError.name = name
|
networkError.name = name;
|
||||||
|
|
||||||
// Rejecting a "respondWith" promise emulates a network error.
|
// Rejecting a "respondWith" promise emulates a network error.
|
||||||
throw networkError
|
throw networkError;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return passthrough()
|
return passthrough();
|
||||||
}
|
}
|
||||||
|
|
||||||
function sendToClient(client, message) {
|
function sendToClient(client, message) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
const channel = new MessageChannel()
|
const channel = new MessageChannel();
|
||||||
|
|
||||||
channel.port1.onmessage = (event) => {
|
channel.port1.onmessage = event => {
|
||||||
if (event.data && event.data.error) {
|
if (event.data && event.data.error) {
|
||||||
return reject(event.data.error)
|
return reject(event.data.error);
|
||||||
}
|
}
|
||||||
|
|
||||||
resolve(event.data)
|
resolve(event.data);
|
||||||
}
|
};
|
||||||
|
|
||||||
client.postMessage(message, [channel.port2])
|
client.postMessage(message, [channel.port2]);
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function sleep(timeMs) {
|
function sleep(timeMs) {
|
||||||
return new Promise((resolve) => {
|
return new Promise(resolve => {
|
||||||
setTimeout(resolve, timeMs)
|
setTimeout(resolve, timeMs);
|
||||||
})
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function respondWithMock(response) {
|
async function respondWithMock(response) {
|
||||||
await sleep(response.delay)
|
await sleep(response.delay);
|
||||||
return new Response(response.body, response)
|
return new Response(response.body, response);
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user