corello
v0.3.2
Published
Main Kernel
Maintainers
Readme
Welcome to Corello!
This library is a shared kernel, and exposes simple object serialization and some helpers.
Setup
Start by installing from npm.
npm install corelloSample Vite project
Click here to check out source code for the sample application (Vue+vite)
@Dto
The @Dto is Stage 2 decorator . This can be used to annotate any class you wish to use as a Dto. The problem with serialization is that we need to write code for handling nested object properties, to instantiate proper instances while serializing a json object. With the Dto decorator, all you have to do is to do one of the following:
@Class(()=>Class)
The @Class can be used to explicitly hint what is the type of the property. In most cases the type can be indicated by the concrete type of the property: This decorator takes a function that returns the class
public user = new User() // the user is initialised as a User instance no need for @Class@Factory((x:T, index:number)=>new Class(x))
The @Factory in case you had a collection like an array of Users, you can pass the a function factory that return a new Class() to decide how the serialization will happen:
//@Class(()=>User)// OK
@Factory((userInArray, _index:number)=>new User(userInArray)) // more control on how to deal
// with every item in json and how to map it to your users field..
public users:IUser[] = []Note: Primitive types are automatically handled.
DtoBase
The @Dto will forge a new method called from that can be used to consume and JSON, to make things easier you need to inherit from DtoBase<TClass>, or you need to implement your own base class to introduce the from method.
JSON.Stringify
Any Dto can be printed with JSON.stringify. Please note that this will also include getters except for one case; any getter prefixed with an underscore _ will not be visible in the result.
Example
import { Class,Factory, Dto, DtoBase } from "./decorators/dto"
interface IUser {
name: string
}
@Dto
class User extends DtoBase<IUser> {
name!: string
}
@Dto
class Car extends DtoBase<Car> {
@Class(()=>User)
user!:IUser
wheels!:string[]
get name(){
return this.user?.name
}
@Factory((x:IUser)=>new User(x))
passengers:IUser[] = []
}
const car = new Car ()
// deserialize the json to a strongly typed object..
car.from({ wheels:['one','two'],user: {name:'Anas'}, passengers:[{name:'semsem'}] })
console.log("To String > ",car.toString())
//Stringify with JSON, Note that getters will exist in the result, unless they are prefixed with a _ character
console.log("JSON ", JSON.stringify(car))Note: In your ts-config make sure to enable the experimental decorators.
