Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get random records from Strapi content API

Tags:

I have records in strapi. I am using strapi content API. In my front-end, I need to display only 2 records randomly. For limiting, I have used limit query from content API. But random fetching what keyword I need to use. The official documentation doesn't provide any details regarding this - https://strapi.io/documentation/v3.x/content-api/parameters.html#available-operators

like image 940
Parthiban Avatar asked Dec 09 '20 14:12

Parthiban


1 Answers

There's no official Strapi API parameter for random. You have to implement your own. Below is what I've done previously, using Strapi v3:

1 - Make a service function

File: api/mymodel/services/mymodel.js

A service is handy because it can be used in many places (cron jobs, inside other models, etc).

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 - Use the service somewhere, like a controller:

File: 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 - Create a route that points to this controller

File: api/mymodel/config/routes.json

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

4 - Then in front-end, you access the route

(However you access your API)

ie /api/mymodelrandom

like image 177
MarsAndBack Avatar answered Sep 29 '22 11:09

MarsAndBack