metadata.ts
1 export interface FieldMetadata { 2 /** 3 * If the field is required but somehow the value we retrieve is `null`, 4 * we use this default value, if provided. 5 */ 6 defaultValue?: (() => any) | any; 7 deserializer?: (value: any, self: InstanceType<any>) => any; 8 enum?: any; 9 key: string; 10 /** 11 * All fields are required by default, using `@optional` will 12 * make the field optional by deserializers and serializers. 13 */ 14 optional?: boolean; 15 rename?: string; 16 } 17 18 export function getModelMetadata(clazz: any): Array<FieldMetadata> { 19 return clazz.constructor._propertyMetadata || []; 20 } 21 22 export function getModelMetadataField(clazz: any, field: string): FieldMetadata | undefined { 23 return getModelMetadata(clazz).find( 24 (local: FieldMetadata) => local.key === field 25 ); 26 } 27 28 export function mutateModelMetadataField(clazz: any, field: string, mutation: (metadata: FieldMetadata) => void): void { 29 if (!clazz.constructor._propertyMetadata) { 30 clazz.constructor._propertyMetadata = []; 31 } 32 33 const metadata = getModelMetadataField(clazz, field); 34 35 if (!metadata) { 36 // Will update the locally created reference. 37 const metadata = { key: field }; 38 mutation(metadata); 39 40 // Then we'll push it to metadatas. 41 clazz.constructor._propertyMetadata.push(metadata); 42 } 43 // Will update the reference. 44 else mutation(metadata); 45 }