codable
Codable base class for TypeScript
installation
yarn add codable
Usage
Import
Import Codable
, CodableType
and CodingKeys
to create codable class.
;
Decode
Decode JSON response body to object.
// Example; ;
Landmark class has the class decorator @CodingKeys
for property key mapping. If you set keys, only those keys properties are going to be converted. If you don't set @CodingKeys
decorator, then every property will be converted.
@CodingKeys({
<Key name of Object>: <Key name of JSON>,
...
})
export class MyClass {
...
Encode
Encode object to dictionary as a JSON request body
;;
This example requestBody will be:
{
"title": "My Favorite",
"founding_date": "2019-01-01",
"location": {
"latitude": 35.360707,
"longitude": 138.727765
},
"vantage_points": [
{
"latitude": 35.442139,
"longitude": 138.850397
},
{
"latitude": 35.460179,
"longitude": 138.832873
}
]
}
Accessor method properties (getter/setter)
Accessor method properties also work with Codable class.
;; ;console.loguser.created_at_raw; // '2019-01-23T04:56:07.000Z'console.loguser.createdAt.getTime; // 1548219367000
In this case, it has an original value in created_at_raw
. And the property createdAt
handles the value as a Date
type.
In another case, if you want to set logic in accessor in decoding/encoding time, Codable can handle Accessor method properties at the time.
You can access inner value directly, and also accessor methods gonna work.
// User.decode({name:'test', created_at: 'dead'}); // throws Error: Invalid Date;console.loguser._created_at.getTime; // 1548219367000console.loguser.created_at; // '2019-01-23T04:56:07.000Z';
The data
will be:
"username": "appleseed" "created_at": "2019-01-23T04:56:07.000Z"