moment.Duration & format
See original GitHub issueHi,
I’ve just tested the changes made to NSwag to handle TimeSpan as moment.Duration in TypeScript (#1460) and there is still a problem in the toJSON function that get’s generated.
The following this.myTimeSpan.format('HH:mm:ss')
doesn’t work, it seems that moment.Duration has no format function. It has been a long and ongoing discussion on the moment GitHub see 463 & 1048.
The solution seems to be to create a moment.Moment and use format on that, it should be the following code: moment.utc(this.myTimeSpan).format('HH:mm:ss')
or to use the Moment Duration Format plugin.
Anyway, an other problem is the loss of days & fractional seconds when doing the format back to Json. This can’t be solved with the trick via moment.utc
, and there the Moment Duration Format is needed.
this.myTimeSpan.format('d.hh:mm:ss.SS')
This should be conform the ASP.NET style time spans.
So I would suggest to change the format in code and to require the usage of the Moment Duration Format plugin. To install the plugin the following npm packages are needed:
npm install moment-duration-format
npm install --save-dev @types/moment-duration-format
And I needed to add the following import in the generated file, just after import * as moment from 'moment';
:
import 'moment-duration-format';
I hoped there was an easier way, but after a lot of research it was the best I could come up with.
Regards,
Jochen
Issue Analytics
- State:
- Created 5 years ago
- Comments:11 (11 by maintainers)
In the NSwag code after the following line the extra import for moment-duration-format also needs to be added. https://github.com/RSuter/NSwag/blob/2f5d7d35bdc07e76de09220d3f517d83eecbc9fc/src/NSwag.CodeGeneration.TypeScript/Templates/File.liquid#L55
But I’m not sure if there is a possibility to include the line only if TimeSpans are being generated? Because otherwise a lot of existing projects that don’t use TimeSpan will have to install the moment-duration-format package.
Ok, i think it’s fine now…