lonestone / nest-sdk-generator

A REST SDK generator for NestJS. Strictly type your frontend's API calls :rocket:
MIT License
90 stars 10 forks source link

Date transformation #13

Open PassiDel opened 12 months ago

PassiDel commented 12 months ago

Hey, great generator! As a frontend dev it is very convenient to simply import all route typesafe from the backend without having to write all types twice!

However, when trying it out, I noticed a problem with Date: With a controller that has a Date object as type, the generator copies it as such. But Nest.js automatically transforms this to an ISO string, whereby the client type is no longer correct (Date instead of string).

Example Controller: ```ts // demo.controller.ts @Controller("demo") export class DemoController { @Get("/route") demo() { return { id: 3, date: new Date() } } } ``` Response: ``` // GET /demo/route { "id": 3, "date": "2023-09-24T15:14:48.940Z" } ``` Generated SDK: ```ts export default { // GET @ /demo/route demo( params: {} = {}, body: {} = {}, query: {} = {}, ): Promise<{ id: number; date: Date }> { return request("GET", `/demo/route`, body, query) }, } ``` Usage: ```ts const { date } = await demoController.demo(); // throws Uncaught TypeError: date.toLocaleDateString is not a function console.log(date.toLocaleDateString()) ```

Would it be possible (and if so how) to transform these Date objects automatically on the client side? Either change all Date types to strings, or ideally recursively parse them directly with new Date(value).

samchon commented 12 months ago

@clement-estone When generating SDK, recommend to wrap every DTO types with Primitive type.

Then, this problem would be solved, due to Date.toJSON(): string method.

https://github.com/samchon/nestia/blob/master/packages/fetcher/src/Primitive.ts