如何从Strapi内容API获取随机记录

8
5个回答

5

没有官方的Strapi API参数可以实现随机。您需要自己实现。以下是我以前使用Strapi v3所做的事情:

1- 创建一个服务函数

文件:api/mymodel/services/mymodel.js

这将包含我们实际的随机查询(SQL),将其包装在服务中很方便,因为它可以在许多地方使用(cron作业,在其他模型内部等)。

module.exports = {
    serviceGetRandom() {

        return new Promise( (resolve, reject) => {
            
            // There's a few ways to query data.
            // This example uses Knex.
            const knex = strapi.connections.default
            let query = knex('mydatatable')

            // Add more .select()'s if you want other fields
            query.select('id')

            // These rules enable us to get one random post
            query.orderByRaw('RAND()')
            query.limit(1)

            // Initiate the query and do stuff
            query
            .then(record => {
                console.log("getRandom() record: %O", record[0])
                resolve(record[0])
            })
            .catch(error => {
                reject(error)
            })
        })
    }
}

2 - 在某处使用该服务,比如在控制器中:

文件:api/mymodel/controllers/mymodel.js

module.exports = {

    //(untested)

    getRandom: async (ctx) => {

        await strapi.services.mymodel.serviceGetRandom()
        .then(output => {
            console.log("getRandom output is %O", output.id)
            ctx.send({
                randomPost: output
            }, 200)
        })
        .catch( () => {
            ctx.send({
                message: 'Oops! Some error message'
            }, 204) // Place a proper error code here
        })

    }

}

3 - 创建一个指向该控制器的路由

文件: api/mymodel/config/routes.json

...
    {
        "method": "GET",
        "path": "/mymodelrandom",
        "handler": "mymodel.getRandom",
        "config": {
            "policies": []
        }
    },
...

4 - 在前端中访问路由

(无论您如何访问API)

例如,ajax调用/api/mymodelrandom


3

没有用于获取随机结果的API参数。

因此,建议您使用FrontEnd来解决您的问题。

您需要创建一个随机请求范围,然后从该范围中获取一些随机项。

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}
const firstID = getRandomInt(restaurants.length);
const secondID = getRandomInt(3);
const query = qs.stringify({
  id_in:[firstID,secondID ] 
});
// request query should be something like GET /restaurants?id_in=3&id_in=6

谢谢。但是我不知道数据的任何信息,比如ID。而且这里的ID不像例子中那样是递增的整数。 - Parthiban
如果这是一个负责任的做法,那么获取所有项目,然后从列表中随机选择如何? - Frizzant
你可以扩大请求范围,而不是获取所有结果,这样可以节省网络时间。 - Cem Kaan
谢谢@CemKaan,但我正在使用运行时获取,这会导致明显的网络延迟。 - Parthiban

2

这对于我来说似乎在 Strapi v.4 REST API 上可行

控制器,获取6个随机条目

"use strict";

/**
 *  artwork controller
 */

const { createCoreController } = require("@strapi/strapi").factories;

module.exports = createCoreController("api::artwork.artwork", ({ strapi }) => {
  const numberOfEntries = 6;
  return {
    async random(ctx) {
      const entries = await strapi.entityService.findMany(
        "api::artwork.artwork",
        {
          populate: ["image", "pageHeading", "seo", "socialMedia", "artist"],
        }
      );

      const randomEntries = [...entries].sort(() => 0.5 - Math.random());
      ctx.body = randomEntries.slice(0, numberOfEntries);
    },
  };
});

Route random.js

"use strict";

module.exports = {
  routes: [
    {
      method: "GET",
      path: "/artwork/random",
      handler: "artwork.random",
      config: {
        auth: false,
      },
    },
  ],
};

API

http://localhost:1337/api/artwork/random

在此输入图片描述 在此输入图片描述

为了匹配Strapi的默认数据结构

"use strict";

/**
 *  artwork controller
 */

const { createCoreController } = require("@strapi/strapi").factories;

module.exports = createCoreController("api::artwork.artwork", ({ strapi }) => {
  const numberOfEntries = 6;
  return {
    async random(ctx) {
      const entries = await strapi.entityService.findMany(
        "api::artwork.artwork",
        {
          populate: ["image", "pageHeading", "seo", "socialMedia", "artist"],
        }
      );

      const randomEntries = [...entries]
        .sort(() => 0.5 - Math.random())
        .slice(0, numberOfEntries);

      const structureRandomEntries = {
        data: randomEntries.map((entry) => {
          return {
            id: entry.id,
            attributes: entry,
          };
        }),
      };

      ctx.body = structureRandomEntries;
    },
  };
});

在这里输入图片描述

此外还有一个随机排序插件。 https://www.npmjs.com/package/strapi-plugin-random-sort


2

您可以通过以下两个步骤可靠地完成此操作:

  1. 获取记录的总数
  2. 使用_start_limit参数获取记录的数量
// Untested code but you get the idea

// Returns a random number between min (inclusive) and max (exclusive)
function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
}

const { data: totalNumberPosts } = await axios.get('/posts/count');

// Fetch 20 posts
const _limit = 20;

// We need to be sure that we are not fetching less than 20 posts
// e.g. we only have 40 posts. We generate a random number that is 30.
// then we would start on 30 and would only fetch 10 posts (because we only have 40)
const _start = getRandomArbitrary(0, totalNumberPosts - _limit);

const { data: randomPosts } = await axios.get('/posts', { params: { _limit, _start } })

这种方法的问题在于需要进行两次网络请求,但对于我的需求来说,这不是一个问题。

1

这对于我来说似乎在 Strapi v4.3.8 和 graphql 中起作用了。

src/index.js

"use strict";

module.exports = {

  register({ strapi }) {
    const extensionService = strapi.service("plugin::graphql.extension");

    const extension = ({ strapi }) => ({
      typeDefs: `
        type Query {
          randomTestimonial: Testimonial
        }
      `,
      resolvers: {
        Query: {
          randomTestimonial: async (parent, args) => {
            const entries = await strapi.entityService.findMany(
              "api::testimonial.testimonial"
            );
            const sanitizedRandomEntry =
              entries[Math.floor(Math.random() * entries.length)];

            return sanitizedRandomEntry;
          },
        },
      },
      resolversConfig: {
        "Query.randomTestimonial": {
          auth: false,
        },
      },
    });

    extensionService.use(extension);
  },
  bootstrap({ strapi }) {},
};

GraphQL查询:

  query GetRandomTestimonial {
    randomTestimonial {
      __typename
      name
      position
      location
      description
    }
  }

在路由更改/刷新时生成随机推荐语

https://jungspooner.com/biography

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接