Hello.
I am trying to resolve a graphQL query. I want to share as much logic as possible between REST and graphQL, therefore I am trying to call a controller in my resolver.
First question - is it a good idea to resolve a query / mutation using a controller? Or should I rather use a service?
Second question - when I get the data from the controller, how does it need to be formatted before it’s returned in gQL response? I have tried following:
'use strict';
module.exports = {
/**
* An asynchronous register function that runs before
* your application is initialized.
*
* This gives you an opportunity to extend code.
*/
register: ({ strapi }) => {
const { transformArgs, getContentTypeArgs } = strapi
.plugin("graphql")
.service("builders").utils;
const extensionService = strapi.plugin("graphql").service("extension");
const extension = ({ nexus }) => ({
// Nexus
types: [
nexus.extendType({
type: "Query",
definition(t) {
t.field("restaurants", {
type: "RestaurantEntityResponseCollection",
args: { slug: nexus.stringArg() },
async resolve(parent, args, ctx) {
const transformedArgs = transformArgs(args, {
contentType:
strapi.contentTypes["api::restaurant.restaurant"],
usePagination: false
})
const {data, meta} = await strapi.controller("api::restaurant.restaurant").find(ctx)
if (data) {
return { restaurants: {data, meta}}
} else {
throw new Error(ctx.koaContext.response.message);
}
}
});
}
})
],
resolversConfig: {
"Query.restaurants": {
auth: false
}
}
});
extensionService.use(extension);
},
/**
* An asynchronous bootstrap function that runs before
* your application gets started.
*
* This gives you an opportunity to set up your data model,
* run jobs, or perform some special logic.
*/
bootstrap(/*{ strapi }*/) {},
};
The problem is that my response always comes empty like this:
{
"data": {
"restaurants": {
"data": []
}
}
}
I am pretty sure that I’m not formatting the response correctly. I have tried several formats like {data: {restaurants: {data, meta}}}
, {restaurants: {data, meta}}
, {data: {data, meta}}
or even just {data, meta}
, but none of them worked. So what is the correct format that needs to be returned from a gQL resolver?