Skip to content

defineFunction(options): object

To define a function you need to create a functions.[js|ts] in each module of your app and return am array called functions, and then define all your functions with calling the defineFunction method.

The defineFunction method serves as a core utility for creating custom functions dynamically. This method allows you to specify various parameters, including the name of the function, the permissions required for access, and the corresponding logic that should be executed when the function is invoked.

Example

Here is an example illustrating how to use the defineFunction method effectively:

typescript
// /modules/myModule/functions.ts

import { defineFunction } from "@modular-rest/server";

const getServerTime = defineFunction({
  name: "getServerTime",
  permissionTypes: ["anonymous_access"],
  callback: (params) => {
    // return your data only
    return `
      Welcome, ${params.username}!
      The current server time is ${new Date().toLocaleString()}.
    `;

    // error handling,
    // client gets error code 400, and the message
    // throw new Error('An error occurred');
  },
});

module.exports.functions = [getServerTime];

In this example, we define a function named getServerTime that requires the user permission type to access. When the function is called, it will return a message containing the current server time and the username of the user who invoked the function.


By utilizing the defineFunction method, developers are empowered to create custom functionality effortlessly within the Modular REST framework, enhancing both the versatility and security of their applications.

Parameters

ParameterTypeDescription
options{ callback: (args) => any; name: string; permissionTypes: string[]; }The function definition options. See DefinedFunction for detailed parameter descriptions.
options.callback(args) => anyThe actual function implementation
options.namestringUnique name of the function
options.permissionTypesstring[]List of permission types required to run the function

Returns

object

The defined function object which system will use to generate a router for the function, generall the client library will use the router to call the function.

NameTypeDescription
callback()(args) => anyThe actual function implementation
namestringUnique name of the function
permissionTypesstring[]List of permission types required to run the function

Throws

If function name already exists, permission types are missing, or callback is invalid