Skip to content

Instantly share code, notes, and snippets.

@sksar
Created January 30, 2023 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sksar/7ca2704aff39edc9b85f46b347bdbdc2 to your computer and use it in GitHub Desktop.
Save sksar/7ca2704aff39edc9b85f46b347bdbdc2 to your computer and use it in GitHub Desktop.
[Directus Hook] Hit Counter on API read
module.exports = async ({ action }, { database: knex }) => {
const collection_key = "page"; // collection key
const id_field_key = "id"; // primary key of the collection
const count_field_key = "read_count"; // must be an integer field
action(`${collection_key}.items.read`, async ({ payload }) => {
const IDs = [];
for (const item of payload){
if(item[id_field_key])
IDs.push(item[id_field_key]);
}
if(IDs.length === 0)
return;
knex(collection_key)
.whereIn(id_field_key, IDs)
.increment(count_field_key, 1)
.catch((err) => {});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment