How to assign the current user id to post api in dreamfactory?

I developed a script that operate under all tables from treat_well._table.{table_name}.post.pre_process
I do not know how it will behave with requests that include related or data_mesh. To direct requests tables worked well.

// POST /api/v2/treat_well/_table triggers script treat_well._table.{table_name}.post.pre_process
// This script runs BEFORE records are written to the treat_well.
// records are in array event.request.payload.

var lodash = require("lodash.min.js");

function tableContainUserId(tableName) {
    var schema = platform.api.get('treat_well/_schema/' + tableName);
    
    return lodash._.chain(schema.content.field)
        .pluck('name')
        .indexOf('user_id')
        .value() > -1;
}

if (event.request.payload && tableContainUserId(event.resource)) {
    lodash._.each(event.request.payload, function(record) {
        record.user_id = platform.session.user.id;
    });
}
1 Like