Topics
Getting started
Dynamic templating
Scripting

Overview

The method script executing prior to generation body response. It's designed to provide the possibility to work with Store Arrays. It should be written in JavaScript.

It can be defined in the Method script field of edit method from

Method script field

Store Arrays is the JSON arrays that could contain up to 100 records or up to 5kb of JSON data. In the method script Store Arrays available as javascript Array object with all corresponding methods. All Store Arrays located in the storeArrays namespace.

For example: To add to Store Array users

Users

Use push method:

storeArrays.users.push(body); // this adds a body JSON to the users Store Array

In method script, you have access to all methods, variables, and namespaces from Templates. For example, to generate new Id you can use random.uuid() which is described in Dynamic templating section :

body.id = random.uuid();
storeArrays.users.push(body);

For further usage in the template you can use a sResult variable, by default it empty object - {}, so you can create custom fields.

const id = random.uuid();
storeArrays.users.push(body);
sResult.id = id;

Then you can use sResult in templates:

Template:

{
  "resultId": "{{sResult.id}}"
}

Making CRUD

With Store Arrays and method scripts you can easily create a simple CRUD API mocks For example Store Array users will be used.


Create

Method script:

body.id = random.uuid();
storeArrays.users.push(body);

Template:

"{{body}}"

Update

Method script:

const index = storeArrays.users.findIndex(u => u.id === params.id);
if (index > -1) {
  body.id = params.id;
  storeArrays.users[index] = body;
  sResult.success = true;
} else {
  sResult.success = false;
  sResult.error = 'Record not found';
}

Template:

"{{sResult}}"

Delete

Method script:

const index = storeArrays.users.findIndex(u => u.id === params.id);
if (index > -1) {
  storeArrays.users.splice(index, 1);
  sResult.success = true;
} else {
  sResult.success = false;
  sResult.error = 'Record not found';
}

Template:

"{{sResult}}"

Read

Method script:

const index = storeArrays.users.findIndex(u => u.id === params.id);
if (index > -1) {
  sResult.data = storeArrays.users[index];
  sResult.success = true;
} else {
  sResult.success = false;
  sResult.error = 'Record not found';
}

Template:

"{{sResult}}"

Read all records

Template:

"{{storeArrays.users}}"