I am building a graphql api. I am using moment and moment range to pick date range from database. But I am facing one problem.
This is graphql Schemas-
gql`
extend type Query {
getAllBookedDate(roomId: ID!): Date
}
`
This is the resolvers
const Moment = require('moment');
const {extendMoment} = require("moment-range");
const moment = extendMoment(Moment);
getAllBookedDate: combineResolvers(isAuthenticated, async (_, {roomId}) => {
const bookings = await Booking.find({room: roomId});
let bookedDates = [];
bookings.forEach(booking => {
const range = moment.range(moment(booking.checkInDate), moment(booking.checkOutDate));
const dates = Array.from(range.by('day'));
bookedDates = bookedDates.concat(Moment([...dates]).toISOString());
});
console.log(bookedDates); /// Result is like folowing codes
return {
bookedDates
}
})
Here I get console.logged result like image-
[
Moment<2016-07-20T18:00:15 06:00>,
Moment<2016-07-21T18:00:15 06:00>,
Moment<2016-07-22T18:00:15 06:00>,
Moment<2016-07-23T18:00:15 06:00>,
Moment<2016-07-24T18:00:15 06:00>,
Moment<2016-07-25T18:00:15 06:00>,
Moment<2016-07-26T18:00:15 06:00>,
Moment<2016-07-27T18:00:15 06:00>,
Moment<2016-07-28T18:00:15 06:00>,
Moment<2016-07-29T18:00:15 06:00>,
Moment<2016-07-30T18:00:15 06:00>
]
Here I am returning this array. I use graphql-iso-date for Scalar in Graphql. I don't know how can I convert above date into iso date. That's why I am facing this problem.
CodePudding user response:
I can see, your date array is not a format date to iso. You have to format date before send it to graphql. So change the code--
gql`
extend type Query {
getAllBookedDate(roomId: ID!): [Date]
}
`
And Resolver:
const Moment = require('moment');
const {extendMoment} = require("moment-range");
const moment = extendMoment(Moment);
getAllBookedDate: combineResolvers(isAuthenticated, async (_, {roomId}) => {
const bookings = await Booking.find({room: roomId});
let bookedDates = [];
bookings.forEach(booking => {
const range = moment.range(moment(booking.checkInDate), moment(booking.checkOutDate));
const dates = Array.from(range.by('day'));
bookedDates = bookedDates.concat(Moment([...dates]).toISOString());
});
bookedDates = bookedDates.map(a => a.toISOString());
return bookedDates;
})
That's it. Try it. I think it work properly now. If not working please let me know. Thank you very much.