Explaining Directus services

What are Directus services?

Directus services are ways to interact with Directus itself.
For example if you want to manage users, items or roles. Services will be the tools you can use for this!
Every service is located in this Github folder.

How to use services

All services are meant for the backend part of Directus.
For extensions this will include Hooks and Endpoints.
They are exposed inside the hook or endpoint.
The services are classes and can be used in the following way:

const mailService = new MailService({ schema });

The schema can be reached with the following 3 ways:
Hooks:

context.schema

Endpoints:

request.schema

If you need the schema but cannot you the ones above, you can also use:

const schema = await extensionContext.getSchema();

ItemsService example

The idea of this example is that every time a item has been created in a collection, there will be a log written. Then trough a custom endpoint you will be able to get all logs.

The full code can be found on GitHub: https://github.com/Attacler/DirectusLogsItemsServiceExample

Hook

import { defineHook } from "@directus/extensions-sdk";export default defineHook(({ action }, { services }) => {
//use ItemsService from the services, we will use this to create the logs
const { ItemsService } = services;
//this action will trigger after the creation of any item
action("items.create", async (payload, { schema }) => {
//make sure to filter out the logs collection to prevent a loop
if (payload.collection == "logs") return;
//initialize the itemsservice for the collection logs and provide the schema
const logs = new ItemsService("logs", { schema });

//create the log
await logs.createOne({
log: payload,
});
});
});

Endpoint

import { defineEndpoint } from "@directus/extensions-sdk";export default defineEndpoint((router, { services }) => {
//use ItemsService from the services, we will use this to read the logs
const { ItemsService } = services;
//listen to http://localhost:8055/getlogs
router.get("/", async (_req, res) => {
//initialize the itemsservice for the collection logs and provide the schema
const logs = new ItemsService("logs", { schema: _req.schema });
//read logs (max 200) and give this back to the res(ponse)
res.json(await logs.readMany());
});
});

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store