Skip to content

Instantly share code, notes, and snippets.

@panchicore
Last active February 9, 2023 20:39
Show Gist options
  • Save panchicore/c922777716ce0066b6647c7723879d43 to your computer and use it in GitHub Desktop.
Save panchicore/c922777716ce0066b6647c7723879d43 to your computer and use it in GitHub Desktop.
strapi custom service to hide ids with another type of sequence
// src/api/project/services/project.ts
export default factories.createCoreService('api::project.project', ({strapi}) => ({
async find(params) {
let {results, pagination} = await super.find(params);
results = results.map(result => ({
...result,
id: result.cuid
}))
return {results, pagination}
},
async findOne(cuid, params) {
const items = await strapi.entityService.findMany('api::project.project', {
filters: {cuid},
fields: ['id'],
limit: 1
})
const itemId = items.length ? items[0].id : 0
let result = await super.findOne(itemId, params);
return ({...result, id: result.cuid})
}
}));
/**
* at the middleware layer
* can also be made at the service layer (above) to use it across any route
*/
import {Strapi} from '@strapi/strapi';
export default (config, {strapi}: { strapi: Strapi }) => {
return async (ctx, next) => {
await next();
if (ctx.response.status === 200) {
ctx.response.body = {
...ctx.response.body,
data: ctx.response.body.data.map(d => ({...d, id: d['attributes']['cuid']}))
}
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment