Skip to main content

Greeting (Part II): Create and Import Shared Modules

Continuing the run task with API route tutorial, we will now learn how to create shared modules for logic.

Learning Objective

To create and manage shared modules - shared data types anf utility functions - for multiple logic.


Why Shared Modules?

In the previous tutorial, we've defined a Person interface (TypeScript) or Person class (C#) as the user-defined data structure and data type. However, we had to declare them in all of the logic, which would be pretty inefficient to maintain the data structure across dozens even hundreds of logic in the future.

Instead, we can import Person from a shared module file, which is an "external" entry file that can be included in any logic building process. The same goes to utility or helper functions that can be shared between logic.

We will now modify the previous tutorial examples by moving Person as well as a JSON parsing utility function into shared module files.

info

Logic still have to be built into a new revision to include the updated shared modules.

Create a Shared Module

See: Create an Entry File

  1. Select JavaScript in logic source.

  2. Create an entry file under the shared_modules folder with the name utils.js.

  3. Copy and paste the following script to replace the template code:

/shared_modules/utils.js
export const ParsePayload = (data) =>
JSON.parse(new TextDecoder().decode(new Uint8Array(data)));

Import a Shared Module

See: Greeting (Part I): Run a Task with an API Route

With the shared modules in place, we can now import them into logic (we'll use the People Parser logic from the previous tutorial):

Generic Logic

person-parser.js (generic logic)
import { LoggingAgent, SessionStorageAgent } from "@fstnetwork/loc-logic-sdk";

// import from shared module
import { ParsePayload } from "../../shared_modules/utils";

/** @param {import('@fstnetwork/loc-logic-sdk').GenericContext} ctx */
export async function run(ctx) {
const payload = await ctx.payload();

if (!("http" in payload))
throw new Error("this logic requires HTTP payload");

const data = payload.http.request.data;

let parsed = null;
if (data) {
try {
// use the imported function
parsed = ParsePayload(data);
} catch (e) {
LoggingAgent.error(
`failed to parse HTTP payload to JSON: ${e.message}`,
);
}
}
LoggingAgent.info({
parsed: parsed,
});

await SessionStorageAgent.putJson("person", {
name: parsed?.name || "User",
});
}

/**
* @param {import('@fstnetwork/loc-logic-sdk').GenericContext} ctx
* @param {import('@fstnetwork/loc-logic-sdk').RailwayError} error
*/
export async function handleError(ctx, error) {
LoggingAgent.error(error.message);
}

Aggregator Logic

greeting-aggregator.js (aggregator logic)
// the JavaScript aggregator is as same as the precious tutorial

Save the changes in the entry file(s), build a new logic revision then update the data process (and triggers if you are using them).