GithubHelp home page GithubHelp logo

Comments (6)

iparker avatar iparker commented on May 28, 2024 1

@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.

benjamincanac avatar benjamincanac commented on May 28, 2024

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.

iparker avatar iparker commented on May 28, 2024

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.

NooBiToo avatar NooBiToo commented on May 28, 2024

Спасибо за ответ!

Я попробовал следующий код в 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

  1. Add Route
  {
    "method": "GET",
    "path": "/article/:url",
    "handler": "articles.one",
    "config": {
      "policies": []
    }
  },

  1. Add Service
  module.exports = {
    /**
    * Promise to fetch record
    *
    * @return {Promise}
    */

    one(params) {
      return strapi.query('articles').findOne(params);
      // return params;
    },
  };

  1. 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;
    },
  };

  1. (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.

benjamincanac avatar benjamincanac commented on May 28, 2024

@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.

iparker avatar iparker commented on May 28, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.