'How to use moment in nestjs application
I want to use momentjs in a nestjs app, and also be able to test my services. So I provided momentjs as below in my module
providers: [
{
provide: 'MomentWrapper',
useFactory: async () => moment(),
scope: Scope.REQUEST,
},
],
and in my service
constructor(
@Inject('MomentWrapper') private momentWrapper: moment.Moment
)
Then I have a method like this
private calculateNextRun(every: number, period: SchedulePeriod): string {
const currentDate = this.momentWrapper.tz('America/Toronto');
let nextDate = null;
nextDate = currentDate.add(every, period);
console.log(currentDate.format(), nextDate.format(), every, period, );
return nextDate.toISOString();
}
This method will be called in a loop, and supposed to get the current date and add some days/weeks/.. to it and return it.
The issue is it keeps the old value so each time it goes into the method is not starting from current date
console output
2020-01-25T16:39:19-05:00 2020-01-25T16:39:19-05:00 6 d
2020-02-15T16:39:19-05:00 2020-02-15T16:39:19-05:00 3 w
2020-02-16T16:39:19-05:00 2020-02-16T16:39:19-05:00 1 d
If you see first date, which is currentDate
keep changing
Is there any way to overcome this issue, without creating a new service like this
import * as moment from 'moment-timezone';
@Injectable()
export class MomentService {
moment(): moment.Moment {
return moment();
}
}
Solution 1:[1]
You should create a new moment instance for each function call and not reuse the same instance of your provider singleton. So provide moment
instead of moment()
:
providers: [
{
provide: 'MomentWrapper',
useValue: moment
},
],
Solution 2:[2]
This works fine for me:
// in some *.service.ts
import * as moment form 'moment';
{ userIsRegistredOn: moment()}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kim Kern |
Solution 2 | Aleksey Kolyasa |