Skip to content

Instantly share code, notes, and snippets.

@evenfrost
Last active January 26, 2022 10:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evenfrost/32d450f2f1b49e3a3e2dbfe68c6facc5 to your computer and use it in GitHub Desktop.
Save evenfrost/32d450f2f1b49e3a3e2dbfe68c6facc5 to your computer and use it in GitHub Desktop.
Custom MikroORM type for Postgres 'jsonb[]'
import { Type, ValidationError } from '@mikro-orm/core';
export default class JsonArrayType extends Type<Record<string, any>[], string> {
convertToDatabaseValue(value: Record<string, any>[]): string {
if (!Array.isArray(value)) {
throw ValidationError.invalidType(JsonArrayType, value, 'JS');
}
const resultValue = JSON.stringify(value)
.replace(/"/g, '\\"')
.replace(/({.*?})/g, '"$&"')
.replace(/^\[/, '{')
.replace(/\]$/, '}');
return resultValue;
}
convertToJSValue(value: Record<string, any>[] | string): Record<string, any>[] {
if (typeof value !== 'string') {
return value;
}
const preparedValue = value
.replace(/^\{/, '[')
.replace(/\}$/, ']')
.replace(/"({.*?})"/g, '$&')
.replace(/\\\\"/, '"');
return JSON.parse(preparedValue) as Record<string, any>[];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment