Comments (6)
@benjamincanac Thanks for this hint. I changed the route to:
{
"method": "GET",
"path": "/articles/:slug",
"handler": "article.findOne",
"config": {
"policies": []
}
And with the following controller it works:
async findOne (ctx) {
const { slug } = ctx.params;
const entity = await strapi.services.article.findOne({ slug });
return sanitizeEntity(entity, { model: strapi.models.article });
},
Thanks for your help!
from strapi.
Hi @iparker,
In order to do so, you have to override the controller of your findOne
route:
async findOne (ctx) {
await strapi.services.restaurant.findOne({ slug: ctx.params.slug })
...
}
Then you will be able to use the strapi module to call the route:
await this.$strapi.findOne('restaurants', '<slug>')
from strapi.
Thanks for your reply!
I tried the following code in controllers/article.js:
const { sanitizeEntity } = require('strapi-utils');
module.exports = {
async findOne (ctx) {
const { slug } = ctx.params;
const entity = await strapi.services.article.findOne({ slug });
return sanitizeEntity(entity, { model: strapi.models.article });
},
};
But with this I get always a different result when I call this route for a slug, for example articles/my-slug.
I'm also wondering why it still "works" with an id. For the route articles/1 I also get differect articles for each request.
I don't know what's the mistake and how to solve this behaviour.
from strapi.
Спасибо за ответ!
Я попробовал следующий код в controllers / article.js:
const { sanitizeEntity } = require('strapi-utils'); module.exports = { async findOne (ctx) { const { slug } = ctx.params; const entity = await strapi.services.article.findOne({ slug }); return sanitizeEntity(entity, { model: strapi.models.article }); }, };
Но при этом я всегда получаю другой результат, когда вызываю этот маршрут для слага, например, article / my-slug.
Еще мне интересно, почему он до сих пор "работает" с id. Для статей маршрута / 1 я также получаю разные статьи по каждому запросу.
Я не знаю, в чем ошибка и как исправить такое поведение.
Hey! I made such a decision for myself, I hope it helps you
I decided not to override routes, but to create a new one
sorry for my bad english
- Add Route
{
"method": "GET",
"path": "/article/:url",
"handler": "articles.one",
"config": {
"policies": []
}
},
- Add Service
module.exports = {
/**
* Promise to fetch record
*
* @return {Promise}
*/
one(params) {
return strapi.query('articles').findOne(params);
// return params;
},
};
- Add Controller
'use strict';
const { parseMultipartData, sanitizeEntity } = require('strapi-utils');
module.exports = {
/**
* Retrieve a record.
*
* @return {Object}
*/
one: async ctx => {
const { url } = ctx.params;
const entity = await strapi.services.articles.one({ url });
// return sanitizeEntity(entity, { model: strapi.models.articles });
return entity;
},
};
- (optional) Add GraphQL
4.1) create file schema.graphql.js in folder config
const { sanitizeEntity } = require('strapi-utils');
module.exports = {
query: `
articleByUrl(url: String name: String): Articles
`,
resolver: {
Query: {
articleByUrl: {
resolverOf: 'Articles.one',
async resolver(_, { url }) {
const entity = await strapi.services.articles.one({ url });
return sanitizeEntity(entity, { model: strapi.models.articles });
},
},
},
},
};
Example query
query ($url: String = "url") {
articleByUrl(url: $url) {
id
title
content
created_at
image {
url
}
}
}
from strapi.
@iparker Did you rename the :id
to :slug
in your route config? If you didn't, then slug
is undefined and the findOne
will return the first result.
from strapi.
One more short question to this: What is the right naming schema.
I want adapt this code to another model named article-category.
The folder name with the json is article-category.
I tried the following code to change the findOne:
const { sanitizeEntity } = require('strapi-utils');
module.exports = {
async findOne (ctx) {
const { slug } = ctx.params;
const entity = await strapi.services.article-category.findOne({ slug });
return sanitizeEntity(entity, { model: strapi.models.article-category });
},
};
I tried different naming variants of the service but nothing worked for me. I always got an 500 internal server error when I call for GET article-catregories/slug.
Hope you can help me with this!
Best regards,
Timo
from strapi.
Related Issues (20)
- How can i use this under server folder ? HOT 1
- How connect Strapi and Nuxt on Remote server
- Nuxt 3 Cookie Disappears on page reload HOT 2
- Where is the 'admin' module option? HOT 1
- Can I customize the Strapi url for only the data requests, yet keep the defaults on everything else?
- Server side request is returning 403
- Generating static output gives localhost adress
- Export types HOT 10
- How to perform transactions in nuxt HOT 1
- How to handle errors when using useAsyncData?
- Problem with useAsyncData when use NuxtLInk
- SSR for user page using useAsyncData & useStrapiAuth (or useStrapiUser)
- How delete with proxy?
- Typescript on pagination.
- Problem with fetch data in production HOT 1
- Strapi v5 Beta
- Looking for maintainers HOT 1
- Mocking strapi with MSW
- Typing response from find HOT 1
- Strapi impersonation HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from strapi.