Created
January 30, 2023 08:31
-
-
Save sksar/7ca2704aff39edc9b85f46b347bdbdc2 to your computer and use it in GitHub Desktop.
[Directus Hook] Hit Counter on API read
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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