Created
April 7, 2025 02:47
-
-
Save Edlavio/5cdfd0b76fb5104c57110dd51e42dd8d to your computer and use it in GitHub Desktop.
Custom route in Strapi - To get a blog post by slug
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// src/api/post/routes/custom-post.ts | |
module.exports = { | |
routes: [ | |
{ | |
method: 'GET', | |
path: '/posts/slug/:slug', | |
handler: 'post.findOneBySlug', | |
config: { | |
policies: [], | |
middlewares: [], | |
auth: false, | |
}, | |
}, | |
], | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// src/api/post/controllers/custom-post.ts | |
/** | |
* post controller | |
*/ | |
import { factories } from '@strapi/strapi' | |
export default factories.createCoreController('api::post.post', ({ strapi }) => ({ | |
async findOneBySlug(ctx) { | |
const { slug } = ctx.params; | |
const { query } = ctx; | |
try { | |
const post = await strapi.db.query('api::post.post').findOne({ | |
where: { slug }, | |
populate: ['image', 'categories'], | |
...query, | |
}); | |
if (!post) { | |
return ctx.notFound(`Post with slug "${slug}" not found`); | |
} | |
const sanitizedEntity = await this.sanitizeOutput(post, ctx); | |
return this.transformResponse(sanitizedEntity); | |
} catch (err) { | |
ctx.throw(500, err); | |
} | |
}, | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment