Skip to content

Pre hook

  • Lines of code will be run before executing the actual API request.
  • Multiple pre hooks can be added.
  • Any time the API Maker user can activate/inactivate, update/delete any pre hook, it will affect in next request. No need to restart the project.
  • Pre hooks run sequentially in top-to-bottom order.
  • API Maker users can add Pre hook in instance APIs, custom APIs, system APIs, and Third party APIs.
  • If any Pre hook has a return statement, and if it will execute then the API call will not happen.

Keep In mind:

  1. Return without any value
    • This means that you only exit the specific hook not from the entire execution.
  2. Return with any value
    • This means that the hook can end the next execution and return a value.
  3. Override pre-hook output
    • Using the [g.res.output] command and do not return a value from Main API will override the pre-hook's output without affecting the next execution.
  4. Override main api output
    • Using the [g.res.output] command and returning a value from Main API will override the main API's output without affecting the next execution.
  5. Throw error
    • This means that the "throw Error" statement will send an error message in the response and stop the next execution.

Note: If API has caching enabled and data is coming from the cache system will not execute pre-hook and post-hook.

Global object 'g'

  • Pre hook has available global object 'g'. API Maker users can use all methods of 'g' in pre hooks.
1
2
3
4
5
6
7
8
9
import * as T from 'types';
async function main(g: T.IAMGlobal) {
    return await g.sys.db.getAll({
        instance: "INSTANCE_NAME",
        collection: "COLLECTION_NAME",
        database: "DATABASE_NAME",
    });
};
module.exports = main;

Use Utility classes

  • Utility classes can be imported and used it's active versions methods.
  • All utility classes are available in the 'utils/' path.
  • Click CTRL+SPACE to get a list of all utility classes.
1
2
3
4
5
6
import * as T from 'types';
import * as addition from 'utils/Addition';
async function main(g: T.IAMGlobal) {
    return addition.add(g.req.body.x, g.req.body.y);
};
module.exports = main;