SapphireDb logo SapphireDb

Class transformer

If you want to transform the raw json values you get from SapphireDb to a typed class you can do this using the described method.
The advantages are type conversions for example from string to integer or date and you are also able to do field mappings if necessary.

Setup

You have to create a custom class transformer that maps the raw json to a typed class.
This example uses class-transformer by typestack

\f:(typescript:transformer.ts) export class CustomClassTransformer extends SapphireClassTransformer {\n \tclassToPlain<T>(value: T[] | T): any {\n \t\treturn classToPlain(value);\n \t}\n\n \tplainToClass<T>(value: any, classType: ClassType<T>): T[] | T {\n \t\treturn plainToClass(classType, value);\n \t}\n } \f:(typescript:app.module.ts) providers: [\n \t{ provide: SapphireClassTransformer, useClass: CustomClassTransformer }\n ]

Demo

This example maps the content of the before used entries to an integer

\f:(typescript:example.component.ts) export class ClassTransformerComponent implements OnInit {\n \tcollection: DefaultCollection<ExampleEntry>;\n \tvalues$: Observable<ExampleEntry[]>;\n\n \tconstructor(private db: SapphireDb) { }\n\n \tngOnInit() {\n \t\t// Pass the class as second parameter\n \t\tthis.collection = this.db.collection('demo.entries', ExampleEntry);\n \t\tthis.values$ = this.collection.values();\n \t}\n } \f:(typescript:example-entry.ts) class ExampleEntry {\n \tid?: string;\n\n \t@Transform((v: string) => parseInt(v, null), { toClassOnly: true })\n \t@Transform((v: number) => `123${v}`, { toPlainOnly: true })\n \tcontent: number;\n\n \tconstructor() {\n \t\tthis.content = 126;\n \t}\n }

This website uses Google Analytics. If you want to disable it just unselect the option: