diff --git a/src/transformer.ts b/src/transformer.ts index ec5d1c8..3bf2f97 100644 --- a/src/transformer.ts +++ b/src/transformer.ts @@ -55,3 +55,42 @@ export class EncryptionTransformer implements ValueTransformer { } } } + +export class JSONEncryptionTransformer implements ValueTransformer { + constructor(private options: EncryptionOptions) {} + + public from(value?: null | any): any | undefined { + if (!value || !value.encrypted) { + return; + } + + const decrypted = decryptData( + Buffer.from(value.encrypted as string, 'base64'), + this.options + ).toString('utf8'); + + return JSON.parse(decrypted); + } + + public to(value?: any | FindOperator | null): Object | FindOperator | undefined { + if ((value ?? null) === null) { + return; + } + + if (typeof value === 'object' && !value?.type) { + const encrypted = encryptData( + Buffer.from(JSON.stringify(value) as string, 'utf8'), + this.options + ).toString('base64'); + + return { encrypted } + } + + if (!value) { + return; + } + + // FindOperators are not supported. + throw new Error('Filter operators are not supported for JSON encrypted fields'); + } +}