Skip to content

Commit

Permalink
Merge pull request #187 from UN-OCHA/HPC-8569-getTableColumns
Browse files Browse the repository at this point in the history
HPC-8569 get table columns function
  • Loading branch information
manelcecs authored Nov 20, 2024
2 parents dc5888a + e8f149a commit 61da672
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/util/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { FieldDefinition } from '../db/util/model-definition';

/**
* This type allows us to restrict assignments of other types.
*
Expand All @@ -21,3 +23,30 @@ export type Brand<T, S extends { s: symbol }, Label extends string = ''> = T & {

export const createBrandedValue = <T, B extends Brand<T, any, any>>(v: T): B =>
v as unknown as B;

export const getTableColumns = <
T extends { _internals: { fields: FieldDefinition } },
>(
table: T
): string[] => {
const {
generated,
generatedCompositeKey,
nonNullWithDefault,
required,
optional,
accidentallyOptional,
} = table._internals.fields;

// Collect columns from all subsets
const columns = [
...Object.keys(generated ?? {}),
...Object.keys(generatedCompositeKey ?? {}),
...Object.keys(nonNullWithDefault ?? {}),
...Object.keys(required ?? {}),
...Object.keys(optional ?? {}),
...Object.keys(accidentallyOptional ?? {}),
];

return columns;
};
34 changes: 34 additions & 0 deletions tests/utils/types.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { getTableColumns } from '../../src/util/types';
import ContextProvider from '../testContext';

const context = ContextProvider.Instance;

describe("Test 'getTableColumns' function", () => {
it('should return the columns of a table', () => {
const columns = getTableColumns(context.models.emergency);

expect(columns).toBeDefined();
expect(columns).toBeInstanceOf(Array);
const expectedColumns = [
'id',
'name',
'date',
'restricted',
'active',
'createdAt',
'updatedAt',
'description',
'glideId',
'levelThree',
];
expectedColumns.forEach((column) => {
expect(columns).toContain(column);
});
});
it('should return an empty array if the table has no columns', () => {
const columns = getTableColumns({ _internals: { fields: {} } });
expect(columns).toBeDefined();
expect(columns).toBeInstanceOf(Array);
expect(columns).toHaveLength(0);
});
});

0 comments on commit 61da672

Please sign in to comment.