How to create custom graphQl API in Strapi CMS

John Ding - Apr 1 '22 - - Dev Community

Say you added a new collection type named "likes" and Strapi automatically creates graphQL API for you, you can customize the API by doing this:

  • Update api/likes/config/schema.graphql.js
    module.exports = {
    query: ['findtest: Likes'],
    mutation: ['updatetest: Likes'],
    resolver: {
    Query: {
    findMyLikes: {
    description: 'Return a list of all my likes',
    resolverOf: 'application::likes.likes.find',
    resolver: 'application::likes.likes.findMyLikes'
    }
    },
    Mutation: {
    deleteMyLikes: {
    description: 'delete all my likes',
    resolverOf: 'application::likes.likes.update',
    resolver: 'application::likes.likes.deleteMyLikes'
    },
    },
    }
    };

  • Update api/likes/controllers/likes.js
    `
    module.exports = {
    findTest: async (ctx) => {
    let t = await strapi.services.likes.findOne({id: 5});
    return t;
    },

updateTest: async (ctx) => {
// const {id, categoryID} = ctx.request.body;
return {
id: 4
}
}
};
`

That is it!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .