UNPKG

@creamapi/cream

Version:

Concise REST API Maker - An extension library for express to create REST APIs faster

63 lines (62 loc) 2.5 kB
"use strict"; /* * Copyright 2024 Raul Radu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); exports.SERIAL_MAP_METADATA_KEY = exports.SERIALIZER_METADATA_KEY = void 0; exports.Serializable = Serializable; exports.AutoMap = AutoMap; exports.MapTo = MapTo; exports.SERIALIZER_METADATA_KEY = Symbol('cream:data-serializer'); exports.SERIAL_MAP_METADATA_KEY = Symbol('cream:data-serial-map'); /** * Declares a class to be serialized and also declares the serializer that * should be used to serialize the decorated class * @param serializer the Serializer that should be used * @returns the decorator that will decorate the class */ function Serializable(serializer) { return function (target) { Reflect.defineMetadata(exports.SERIALIZER_METADATA_KEY, new serializer(target.name, target), target.prototype); return target; }; } /** * This method is used to declare a field serializable * and it will also get the name of the field automatically * @param target the target class attribute * @param propertyName the name of the class attribute * @returns the decorator that will handle the mapping for serialization */ function AutoMap(target, propertyName) { return MapTo(propertyName)(target, propertyName); } /** * This method is used to declare a field serializable * and it will also get the name of the field automatically but it will * map to a different name declared by the user * @param name the new name of the field in the serialized object * @returns the decorator that will handle the mapping for serialization */ function MapTo(name) { return function (target, propertyName) { let serialMap = Reflect.getOwnMetadata(exports.SERIAL_MAP_METADATA_KEY, target) || []; serialMap.push({ fieldName: propertyName, outName: name, }); Reflect.defineMetadata(exports.SERIAL_MAP_METADATA_KEY, serialMap, target); }; }