Объяснение услуг Directus

Что такое услуги Директус?

Службы Directus — это способы взаимодействия с самим Directus.
Например, если вы хотите управлять пользователями, элементами или ролями. Сервисы будут инструментами, которые вы можете использовать для этого!
Каждый сервис находится в этой папке Github.

Как пользоваться услугами

Все сервисы предназначены для серверной части Directus.
Для расширений это будет включать хуки и конечные точки.
Они доступны внутри хука или конечной точки.
Сервисы являются классами и могут использоваться в следующим образом:

const mailService = new MailService({ schema });

Доступ к схеме можно получить тремя способами:
Хуки:

context.schema

Конечные точки:

request.schema

Если вам нужна схема, но вы не можете использовать приведенные выше, вы также можете использовать:

const schema = await extensionContext.getSchema();

Пример службы товаров

Идея этого примера заключается в том, что каждый раз, когда элемент создается в коллекции, будет записываться журнал. Затем через пользовательскую конечную точку вы сможете получить все журналы.

Полный код можно найти на GitHub: https://github.com/Attacler/DirectusLogsItemsServiceExample

Крюк

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,
    });
  });
});

Конечная точка

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());
  });
});