How can I declare the code below once so I do not have to repeat them in each custom graphql resolver?
const { toEntityResponseCollection } = strapi.plugin("graphql").service("format").returnTypes;
const { toEntityResponse } = strapi.plugin("graphql").service("format").returnTypes;
I have multiple custom resolvers and in each of them I have to include the logic above so my return type will display correctly; otherwise, I will get Data: null. I want to declare them once and use them over and over without repeating the logic.
Code with repeating logic:
const axios = require("axios");
const EXTERNAL_API_URL = "http://jsonplaceholder.typicode.com/users";
exports.Query = {
endUsers: async () => {
const { data } = await axios.get(EXTERNAL_API_URL);
const { toEntityResponseCollection } = strapi
.plugin("graphql")
.service("format").returnTypes;
if (data) {
console.log(data);
return toEntityResponseCollection(data);
} else {
throw NotFoundError();
}
},
endUser: async (parent, args, context) => {
console.log("id: ", args.id);
const url = `${EXTERNAL_API_URL}/${args.id}`;
const { toEntityResponse } = strapi
.plugin("graphql")
.service("format").returnTypes;
const { data } = await axios.get(url);
console.log("url", url);
if (data) {
console.log(data);
return toEntityResponse(data);
} else {
throw NotFoundError();
}
},
};
Thank you.