Search code examples
directus

Best way to retrieve and filter a directus collection inside a custom endpoint?


I would need to search an item inside a collection and then work on that item.

What is the correct way to query a collection inside a custom endpoint? Should i use the API or do you provide any classes?

I tried to follow the current guide https://github.com/directus/docs/blob/master/api/data.md but i get a 403 (Forbidden) error.


Solution

  • I came around the same problem and now working with directus for some time. I asked the same question at the discussion section but the example in the guidebook should help:

    export default (router, { services, exceptions }) => {
        const { ItemsService } = services;
        const { ServiceUnavailableException } = exceptions;
    
        router.get('/', (req, res, next) => {
            const recipeService = new ItemsService('recipes', { schema: req.schema, accountability: req.accountability });
    
            recipeService
                .readByQuery({ sort: ['name'], fields: ['*'] })
                .then((results) => res.json(results))
                .catch((error) => {
                    return next(new ServiceUnavailableException(error.message));
                });
        });
    };
    

    Maybe it is a bit late but hopefully it inspires others. Directus is from my first experiences now really great and worth to try.