I am looking for a way the Strapi API returns a key/value pair which is calculate and added to the server response but not fetched from the Database:
I have done something like that using ApolloServer
with Prisma
. If you are wondering how I have done? then here is my setup:
Note: I am not looking for how
slug
feature in Strapi but in general I like to know how dynamic/calculate fields can be added to Strapi API Server response.
file: ./src/resolvers/Team.js
const Team = {
slug(parent) {
return parent.title.replace(/\s+/g, '-').toLowerCase();
},
};
export { Team as default };
file: ./src/resolvers/index.js
import { extractFragmentReplacements } from 'prisma-binding';
import Query from './Query';
import Mutation from './Mutation';
import Team from './Team';
const resolvers = {
Query,
Mutation,
// static
Team,
};
const fragmentReplacements = extractFragmentReplacements(resolvers);
export { resolvers, fragmentReplacements };
file: ./src/prisma.js
import { Prisma } from 'prisma-binding';
import { fragmentReplacements } from './resolvers/index';
require('dotenv').config({ path: './.env' });
const prisma = new Prisma({
typeDefs: 'src/generated/prisma.graphql',
endpoint: process.env.API_URL,
secret: process.env.PRISMA_MANAGEMENT_API_SECRET,
fragmentReplacements,
});
export { prisma as default };
file: ./src/schema.graphql
type Team {
id: ID!
title: String!
color: String!
slug: String! // this is not in Db but taken care by `./src/resolvers/StaticTeam.js`
}
As you can see above that how I get the slug
though that's not in database. I just like to have calculated key:val
added to my API.