import { JSONSchema4 } from 'json-schema'; import { describe, expect, test } from 'vitest'; import { PgType } from '../abstractions'; import { getPropertySchema, mapToPgType } from './json-schema-parse-utils'; describe('mapToPgType', () => { interface TestInput { schemaJson: string; expectedPgType: PgType; } // I wish there was a better way - https://github.com/facebook/jest/issues/6413 const testData: [string, TestInput][] = [ [ 'parse integer', { schemaJson: ` { "$schema": "http://json-schema.org/draft-04/schema", "properties": { "prop":{ "type": "integer" } } } `, expectedPgType: 'INTEGER', }, ], [ 'parse integer array', { schemaJson: ` { "$schema": "http://json-schema.org/draft-04/schema", "properties": { "prop": { "type": "array", "items": { "type": "integer" } } } } `, expectedPgType: 'INTEGER[]', }, ], [ 'parse string', { schemaJson: ` { "$schema": "http://json-schema.org/draft-04/schema", "properties": { "prop": { "type": "string" } } } `, expectedPgType: 'TEXT', }, ], [ 'parse string array', { schemaJson: ` { "$schema": "http://json-schema.org/draft-04/schema", "properties": { "prop": { "type": "array", "items": { "type": "string" } } } } `, expectedPgType: 'TEXT[]', }, ], [ 'parse boolean', { schemaJson: ` { "$schema": "http://json-schema.org/draft-04/schema", "properties": { "prop": { "type": "boolean" } } } `, expectedPgType: 'BOOLEAN', }, ], [ 'parse date', { schemaJson: ` { "$schema": "http://json-schema.org/draft-04/schema", "properties": { "prop": { "type": "string", "format": "date-time" } } } `, expectedPgType: 'TIMESTAMPTZ', }, ], ]; test.each(testData)('%s', (_description: string, input: TestInput) => { // Arrange const schema = JSON.parse(input.schemaJson) as JSONSchema4; // Act const pgType = mapToPgType(getPropertySchema(schema, 'prop')); // Assert expect(pgType).toBe(input.expectedPgType); }); }); describe('getPropertySchema', () => { test('Returns existing property', () => { // Arrange const schema = JSON.parse(` { "$schema": "http://json-schema.org/draft-04/schema", "properties": { "prop":{ "type": "integer" } } }`) as JSONSchema4; // Act const propertySchema = getPropertySchema(schema, 'prop'); // Assert expect(propertySchema).toBeDefined(); }); test('Throws if properties are not defined', () => { // Arrange const schema = JSON.parse(` { "$schema": "http://json-schema.org/draft-04/schema" }`) as JSONSchema4; // Act const action = () => getPropertySchema(schema, 'prop'); // Assert expect(action).toThrow(Error); }); test('Returns undefined if property does not exist', () => { // Arrange const schema = JSON.parse(` { "$schema": "http://json-schema.org/draft-04/schema", "properties": { "prop":{ "type": "integer" } } }`) as JSONSchema4; // Act const propertySchema = getPropertySchema(schema, 'does_not_exist'); // Assert expect(propertySchema).toBeUndefined(); }); });