Skip to content

Server API Reference

Table of Contents

  1. Server API
  2. Project API
  3. Log API
  4. Room API
  5. Session API
  6. Emit API
  7. Database API
  8. Request API
  9. Public Files API
  10. Private Files API

Server API

$server.id

Description: Returns the unique identifier of the current server.

Example:

javascript
let serverId = $server.id;

$server.country

Description: Returns the country code where the server is located.
e.g. "NL" for Netherlands, "SG" for Singapore.

Example:

javascript
let serverCountry = $server.country;

$server.getRooms()

Description: Returns a list of rooms created on the current server.

Returns: An array of $room objects.

Example:

javascript
let rooms = $server.getRooms();

$server.getSession(sessionIds)

Description: Retrieves a session or a list of sessions based on the provided session IDs. This method works only within the current server.

Parameters:

  • sessionIds: A single session ID or an array of session IDs.

Returns: A single $session object or an array of $session objects.

Example:

javascript
let session = $server.getSession('sessionId1');
let sessions = $server.getSession(['sessionId1', 'sessionId2']);

Project API

$project.id

Description: Returns the unique identifier of the current project.

Example:

javascript
let projectId = $project.id;

$project.alias

Description: Returns the alias of the current project.

Example:

javascript
let projectAlias = $project.alias;

$project.name

Description: Returns the name of the current project.

Example:

javascript
let projectName = $project.name;

Log API

Logs are available in the Console under Project / Storage / Logs.

Log Rotation Policy: Logs are cleared when the application starts and rotated every 500 lines.

$log.info(...args)

Description: Logs information messages.

Parameters:

  • ...args: The information to log.

Example:

javascript
$log.info('Information message', variable);

$log.debug(...args)

Description: Logs debug messages.

Parameters:

  • ...args: The debug information to log.

Example:

javascript
$log.debug('Debug message', variable);

$log.error(...args)

Description: Logs error messages.

Parameters:

  • ...args: The error information to log.

Example:

javascript
$log.error('Error message', error);

Room API

$room.id

Description: Returns the unique identifier of the current room.

Example:

javascript
let roomId = $room.id;

$room.alias

Description: Returns the alias of the current room.

Example:

javascript
let roomAlias = $room.alias;

$room.setVar(key, value)

Description: Assigns a variable to the room on the current instance.

Parameters:

  • key: The name of the variable.
  • value: The value of the variable.

Example:

javascript
$room.setVar('GameState', 1);

Alternatively, if you're not using pre-defined variables, you can use $room object:

javascript
$room.variableName = 'value';

Or even define some functions, which can be accessed from the current instance:

javascript
$room.myFunctions = {
    fn1: () => {
        // some internal function
    }
};

$room.getVar(key)

Description: Retrieves the value of a room variable on the current instance.

Parameters:

  • key: The name of the variable.

Example:

javascript
let gameState = $room.getVar('GameState');

Alternatively, if you're not using pre-defined variables, you can use $room object:

javascript
let value = $room.variableName;

async $room.getGlobalVar(key)

Description: Retrieves the value of pre-defined Global Room Variables.

Parameters:

  • key: The name of the variable.

Returns: A promise that resolves to the value of the variable.

Example:

javascript
$room.getVar('players').then(value => {
    $log.info(value);
});

async $room.setGlobalVar(key, value)

Description: Assigns a variable inside the room, it will be available for all sessions connected to the room.

Parameters:

  • key: The name of the variable.
  • value: The value of the variable.

Returns: A promise that resolves to a boolean indicating the success of the operation.

Example:

javascript
$room.setVar('players', [{
    id: 1,
    name: 'abc'
}]).then(result => {
    if (result) {
        $log.info('Variable set successfully');
    } else {
        $log.error('Failed to set variable');
    }
});

You can also modify $room object, but these changes will be visible only in the current instance:

javascript
$room.variableName = 'some value';

$room.getSessionIds()

Description: Returns the list of session IDs connected to the current room on the current server.

Example:

javascript
let sessionIds = $room.getSessionIds();

$room.getCCU()

Description: Returns the current number of concurrent users (CCU) in the room on the current server.

Example:

javascript
let ccu = $room.getCCU();

$room.broadcast(command, params = {}, options = {})

Description: Broadcasts a message to the room via the primary transport service. By default, this method works only within the current server unless specified otherwise in the options.

Parameters:

  • command: The alias of the client command defined in the room's logic.
  • params: Key-value pairs of parameters required by the command.
  • options: Options for broadcasting the message.
    • excludeIds: List of session IDs to exclude from the broadcast. Can be a single ID or an array of IDs.
    • cluster: If set to true, the message is broadcast across all servers in the cluster.
    • reliable: If set to true, the message is sent via a reliable channel, WebSocket will be used instead of WebRTC Data Channel.
    • transport: Defines the transport service to use. Can be a string, array of strings, or boolean. Multiple transports can be created in the Project's Settings.

Example: Broadcasting within the current server:

javascript
$room.broadcast('UpdatePlayer', {
    id: $session.id,
    x: $params.x,
    y: $params.y,
    z: $params.z,
    state: $params.state
});

Example: Broadcasting to all regions:

javascript
$room.broadcast('UpdatePlayer', {
    id: $session.id,
    x: $params.x,
    y: $params.y,
    z: $params.z,
    state: $params.state
}, {
    cluster: true,
});

Example with all options:

javascript
$room.broadcast('UpdatePlayer', {
    id: $session.id,
    x: $params.x,
    y: $params.y,
    z: $params.z,
    state: $params.state
}, {
    excludeIds: $session.id,
    cluster: true,
    reliable: true,
    transport: ['ws1', 'ws2']
});

$room.broadcast(commands, options = {})

Description: This is the same method broadcast, but with multiple commands.

Parameters:

  • commands: An array of command with parameters to broadcast.

    • command: The alias of the client command defined in the room's logic.
    • params: Key-value pairs of parameters required by the command.
  • options: Options for broadcasting the message.

    • excludeIds: List of session IDs to exclude from the broadcast. Can be a single ID or an array of IDs.
    • cluster: If set to true, the message is broadcast across all servers in the cluster.
    • reliable: If set to true, the message is sent via a reliable channel, WebSocket will be used instead of WebRTC Data Channel.
    • transport: Defines the transport service to use. Can be a string, array of strings, or boolean. Multiple transports can be created in the Project's Settings.

Example: Broadcasting multiple commands within the current server

javascript
$room.broadcast([
    {
        command: 'UpdatePlayer',
        params: {
            id: $session.id,
            x: $params.x,
            y: $params.y,
            z: $params.z,
            state: $params.state
        }
    },
    {
        command: 'OtherCommandWithoutParams',
    },
]);

Example: Broadcasting multiple commands to all regions

javascript
$room.broadcast([
    {
        command: 'UpdatePlayer',
        params: {
            id: $session.id,
            x: $params.x,
            y: $params.y,
            z: $params.z,
            state: $params.state
        }
    },
    {
        command: 'OtherCommandWithoutParams',
    },
], {
    cluster: true,
});

Example: Broadcasting multiple commands with all options

javascript
$room.broadcast([
    {
        command: 'UpdatePlayer',
        params: {
            id: $session.id,
            x: $params.x,
            y: $params.y,
            z: $params.z,
            state: $params.state
        }
    },
    {
        command: 'OtherCommandWithoutParams',
    },
], {
    excludeIds: $session.id,
    cluster: true,
    reliable: true,
    transport: ['ws1', 'ws2']
});

Session API

$session.id

Description: Returns the unique identifier of the current session.

Example:

javascript
let sessionId = $session.id;

$session.server.id

Description: Returns the unique identifier of the server where the current session is connected.

Example:

javascript
let serverId = $session.server.id;

$session.setVar(key, value)

Description: Assigns a variable to the session.

Parameters:

  • key: The name of the variable.
  • value: The value of the variable.

Example:

javascript
$session.setVar('score', 100);

Alternatively, if you're not using pre-defined variables, you can use $session object:

javascript
$session.variableName = 'value';

$session.getVar(key)

Description: Retrieves the value of a session variable.

Parameters:

  • key: The name of the variable.

Example:

javascript
let score = $session.getVar('score');

Alternatively, if you're not using pre-defined variables, you can use $session object:

javascript
let value = $session.variableName;

$session.emit(command, params = {}, options = {})

Description: Emits a message to the current session. By default, this method works only within the current server unless specified otherwise in the options.

Parameters:

  • command: The alias of the client command defined in the room's logic.
  • params: Key-value pairs of parameters required by the command.
  • options: Options for emitting the message.
    • reliable: If set to true, the message is sent via a reliable channel, WebSocket will be used instead of WebRTC Data Channel.
    • transport: Defines the transport service to use. Can be a string, array of strings, or boolean. Multiple transports can be created in the Project's Settings.

Example:

javascript
$session.emit('Pong', {
    time: $params.time
});

Example: Emit via WebSocket transport with alias "ws1"

javascript
$session.emit('Pong', {
    time: $params.time
}, {
    transport: 'ws1'
});

Example: Emit using reliable channel

javascript
$session.emit('Pong', {
    time: $params.time
}, {
    reliable: true
});

$session.emit(commands, options = {})

Description: This is the same method emit, but with multiple commands.

Parameters:

  • commands: An array of command with parameters to emit.

    • command: The alias of the client command defined in the room's logic.
    • params: Key-value pairs of parameters required by the command.
  • options: Options for emitting the message.

    • reliable: If set to true, the message is sent via a reliable channel, WebSocket will be used instead of WebRTC Data Channel.
    • transport: Defines the transport service to use. Can be a string, array of strings, or boolean. Multiple transports can be created in the Project's Settings.

Example: Emit multiple commands

javascript
$session.emit([
    {
        command: 'Pong',
        params: {
            time: $params.time
        }
    },
    {
        command: 'SomeCommandWithoutParams',
    },
    {
        command: 'SomeCommandWithParams',
        params: {
            key: 'value'
        }
    }
]);

Example: Emit multiple commands via WebSocket transport with alias "ws1"

javascript
$session.emit([
    {
        command: 'Pong',
        params: {
            time: $params.time
        }
    },
    {
        command: 'SomeCommandWithoutParams',
    },
    {
        command: 'SomeCommandWithParams',
        params: {
            key: 'value'
        }
    }
], {
    transport: 'ws1'
});

Example: Emit multiple commands using reliable channel

javascript
$session.emit([
    {
        command: 'Pong',
        params: {
            time: $params.time
        }
    },
    {
        command: 'SomeCommandWithoutParams',
    },
    {
        command: 'SomeCommandWithParams',
        params: {
            key: 'value'
        }
    }
], {
    reliable: true
});

$session.broadcast(command, params = {}, options = {})

Description: Broadcasts a message to the room via the primary transport service, excluding the current session. By default, this method works only within the current server unless specified otherwise in the options.

Parameters:

  • command: The alias of the client command defined in the room's logic.
  • params: Key-value pairs of parameters required by the command.
  • options: Options for broadcasting the message.
    • excludeIds: List of session IDs to exclude from the broadcast. Can be a single ID or an array of IDs.
    • cluster: If set to true, the message is broadcast across all servers in the cluster.
    • reliable: If set to true, the message is sent via a reliable channel, WebSocket will be used instead of WebRTC Data Channel.
    • transport: Defines the transport service to use. Can be a string, array of strings, or boolean. Multiple transports can be created in the Project's Settings.

Example: Broadcasting within the current server:

javascript
$session.broadcast('UpdatePlayer', {
    id: $session.id,
    x: $params.x,
    y: $params.y,
    z: $params.z,
    state: $params.state
});

Example: Broadcasting to all regions:

javascript
$session.broadcast('UpdatePlayer', {
    id: $session.id,
    x: $params.x,
    y: $params.y,
    z: $params.z,
    state: $params.state
}, {
    cluster: true,
});

Example with all options:

javascript
$session.broadcast('UpdatePlayer', {
    id: $session.id,
    x: $params.x,
    y: $params.y,
    z: $params.z,
    state: $params.state
}, {
    excludeIds: $session.id,
    cluster: true,
    reliable: true,
    transport: ['ws1', 'ws2']
});

$session.broadcast(commands, options = {})

Description: This is the same method broadcast, but with multiple commands.

Parameters:

  • commands: An array of command with parameters to broadcast.

    • command: The alias of the client command defined in the room's logic.
    • params: Key-value pairs of parameters required by the command.
  • options: Options for broadcasting the message.

    • excludeIds: List of session IDs to exclude from the broadcast. Can be a single ID or an array of IDs.
    • cluster: If set to true, the message is broadcast across all servers in the cluster.
    • reliable: If set to true, the message is sent via a reliable channel, WebSocket will be used instead of WebRTC Data Channel.
    • transport: Defines the transport service to use. Can be a string, array of strings, or boolean. Multiple transports can be created in the Project's Settings.

Example: Broadcasting multiple commands within the current server

javascript
$session.broadcast([
    {
        command: 'UpdatePlayer',
        params: {
            id: $session.id,
            x: $params.x,
            y: $params.y,
            z: $params.z,
            state: $params.state
        }
    },
    {
        command: 'Ping',
    },
]);

Example: Broadcasting multiple commands to all regions

javascript
$session.broadcast([
    {
        command: 'UpdatePlayer',
        params: {
            id: $session.id,
            x: $params.x,
            y: $params.y,
            z: $params.z,
            state: $params.state
        }
    },
    {
        command: 'Ping',
    },
], {
    cluster: true,
});

Example: Broadcasting multiple commands with all options

javascript
$session.broadcast([
    {
        command: 'UpdatePlayer',
        params: {
            id: $session.id,
            x: $params.x,
            y: $params.y,
            z: $params.z,
            state: $params.state
        }
    },
    {
        command: 'Ping',
    },
], {
    excludeIds: $session.id,
    cluster: true,
    reliable: true,
    transport: ['ws1', 'ws2']
});

$session.leaveRoom()

Description: Removes the current session from the room it is currently connected to.

Example:

javascript
$session.leaveRoom();

$session.joinRoom(roomAlias, roomId = '')

Description: Joins the current session to the specified room on the current server.
Room will be created if it does not exist.

Parameters:

  • roomAlias (string): The Alias of the room to join, as defined in the Console.
  • roomId (string): The ID of the room to join. Unique ID will be automatically generated if not provided.

Example:

javascript
$session.joinRoom('RoomAlias', '12345');

$session.close()

Description: Closes the current session.

Example:

javascript
$session.close();

Emit API

$emit(serverId, sessionId, command, params = {}, options = {})

Description: Emits a command to a specific session on a specific server.

Session must be connected to the Room ID on the specified server.

You need to have Massive Cluster enabled in your project to emit across different locations.
Otherwise, the command can be sent to the server in the same location only.

Parameters:

  • serverId: The unique identifier of the server.
  • sessionId: The unique identifier of the session.
  • command: The alias of the client command defined in the room's logic.
  • params: Key-value pairs of parameters required by the command.
  • options: Options for emitting the message.
    • reliable: If set to true, the message is sent via a reliable channel, WebSocket will be used instead of WebRTC Data Channel.
    • transport: Defines the transport service to use. Can be a string, array of strings, or boolean. Multiple transports can be created in the Project's Settings.

Example:

javascript
$emit('ap.sin-6.2', 'a72oNj3', 'Hello', {
    message: 'Hello, World!'
});

Example: Emit via WebSocket transport with alias "ws1"

javascript
$emit('ap.sin-6.2', 'a72oNj3', 'Hello', {
    message: 'Hello, World!'
}, {
    transport: 'ws1'
});

Example: Emit using reliable channel

javascript
$emit('ap.sin-6.2', 'a72oNj3', 'Hello', {
    message: 'Hello, World!'
}, {
    reliable: true
});

$emit(serverId, sessionId, commands, options = {})

Description: This is the same method emit, but with multiple commands.

Session must be connected to the Room ID on the specified server.

You need to have Massive Cluster enabled in your project to emit across different locations.
Otherwise, the command can be sent to the server in the same location only.

Parameters:

  • serverId: The unique identifier of the server.

  • sessionId: The unique identifier of the session.

  • commands: An array of command with parameters to emit.

    • command: The alias of the client command defined in the room's logic.
    • params: Key-value pairs of parameters required by the command.
  • options: Options for emitting the message.

    • reliable: If set to true, the message is sent via a reliable channel, WebSocket will be used instead of WebRTC Data Channel.
    • transport: Defines the transport service to use. Can be a string, array of strings, or boolean. Multiple transports can be created in the Project's Settings.

Example: Emit multiple commands

javascript
$emit('ap.sin-6.2', 'a72oNj3', [
    {
        command: 'SendText',
        params: {
            message: 'Hello, World!'
        }
    },
    {
        command: 'SendText',
        params: {
            message: 'Second message'
        }
    },
    {
        command: 'Ping',
    }
]);

Example: Emit multiple commands via WebSocket transport with alias "ws1"

javascript
$emit('ap.sin-6.2', 'a72oNj3', [
    {
        command: 'SendText',
        params: {
            message: 'Hello, World!'
        }
    },
    {
        command: 'SendText',
        params: {
            message: 'Second message'
        }
    },
    {
        command: 'Ping',
    }
], {
    transport: 'ws1'
});

Example: Emit multiple commands using reliable channel

javascript
$emit('ap.sin-6.2', 'a72oNj3', [
    {
        command: 'SendText',
        params: {
            message: 'Hello, World!'
        }
    },
    {
        command: 'SendText',
        params: {
            message: 'Second message'
        }
    },
    {
        command: 'Ping',
    }
], {
    reliable: true
});

Database API

The Database API allows you to interact with the database associated with your project.
Database queries are executed asynchronously and return a promise that resolves to the query result.

Maximum key length is 256 characters. Maximum value size is 32KB.

$db.set(dbName, tableName, key, value, ttl = 86400)

Description: Stores a key-value pair in the specified table within the database.

Parameters:

  • dbName (string): The name of the database.
  • tableName (string): The name of the table.
  • key (string): The key under which the value will be stored.
  • value (any): The value to store. Any non-string value will be automatically serialized to JSON.
  • ttl (number, optional): The time in seconds after which the entry will expire and be automatically deleted. Minimum is 1 second, maximum is 86,400 seconds (24 hours). Default is 86400.

Returns: A promise that resolves when the operation is complete.

Example:

javascript
$db.set('myDatabase', 'myTable', 'myKey', { name: 'Alice', score: 100 }).then(result => {
  if (result) {
    $log.info('Entry stored successfully');
  } else {
    $log.error('Failed to store entry');
  }
});

Example with expiration:

javascript
$db.set('myDatabase', 'myTable', 'winnerName', 'Alice', 30).then(result => {
  if (result) {
    $log.info('Entry stored successfully');
  } else {
    $log.error('Failed to store entry');
  }
});

$db.getOne(dbName, tableName, key)

Description: Retrieves a single value from the specified table that matches the key.

Parameters:

  • dbName (string): The name of the database.
  • tableName (string): The name of the table.
  • key (string): The key to retrieve.

Returns: A promise that resolves to the value associated with the key.
Result is the value of the entry.

Example:

javascript
$db.getOne('myDatabase', 'myTable', 'myKey').then(result => {
  $log.info(result);
});

$db.get(dbName, tableName, keyPattern, offset = 0, limit = 100)

Description: Retrieves values from the specified table that match the key pattern.

Parameters:

  • dbName (string): The name of the database.
  • tableName (string): The name of the table.
  • keyPattern (string): The pattern to match keys against. Use * as a wildcard.
  • offset (number, optional): The number of entries to skip.
  • limit (number, optional): The maximum number of entries to return. Default is 100.

Returns: A promise that resolves to an array of matching values.
Each value is an object with the following properties:

  • key: The key of the entry.
  • value: The value of the entry.

Example:

javascript
$db.get('myDatabase', 'myTable', 'key:*').then(records => {
  $log.info(records);
});

Example with offset and limit:

javascript
$db.get('myDatabase', 'myTable', 'myKey*', 0, 10).then(records => {
  $log.info(records);
});

$db.getRandom(dbName, tableName, count = 1)

Description: Retrieves a random record from the specified table.

Parameters:

  • dbName (string): The name of the database.
  • tableName (string): The name of the table.
  • count (number, optional): The number of random records to retrieve. Default is 1.

Returns: A promise that resolves to a random records from the table.
Result is list of objects with the following properties:

  • key: The key of the entry.
  • value: The value of the entry.

Example:

javascript
$db.getRandom('myDatabase', 'myTable', 1).then(result => {
  $log.info(result);
});

$db.count(dbName, tableName)

Description: Counts the number of entries in the specified table.

Parameters:

  • dbName (string): The name of the database.
  • tableName (string): The name of the table.

Returns: A promise that resolves to the count of entries.

Example:

javascript
$db.count('myDatabase', 'myTable').then(count => {
  $log.info('Number of entries:', count);
});

$db.delete(dbName, tableName, key)

Description: Deletes a key-value pair from the specified table.

Parameters:

  • dbName (string): The name of the database.
  • tableName (string): The name of the table.
  • key (string): The key of the entry to delete.

Returns: A promise that resolves when the operation is complete.

Example:

javascript
$db.delete('myDatabase', 'myTable', 'myKey').then(result => {
  if (result) {
    $log.info('Entry deleted');
  } else {
    $log.error('Failed to delete entry');
  }
});

$db.truncate(dbName, tableName)

Description: Deletes all entries from the specified table.

Parameters:

  • dbName (string): The name of the database.
  • tableName (string): The name of the table.

Returns: A promise that resolves when the operation is complete.

Example:

javascript
$db.truncate('myDatabase', 'myTable').then((result) => {
  if (result) {
    $log.info('Table truncated');
  } else {
    $log.error('Failed to truncate table');
  }
});

$db.increment(dbName, tableName, key, value = 1, ttl = 86400)

Description: Increments the value of a numerical key in the specified table.

Parameters:

  • dbName (string): The name of the database.
  • tableName (string): The name of the table.
  • key (string): The key of the entry to increment.
  • value (number): The amount to increment by. Number can be integer or float. Default is 1.
  • ttl (number, optional): The time in seconds after which the entry will expire and be automatically deleted. Minimum is 1 second, maximum is 86,400 seconds (24 hours). Default is 86400.

Returns: A promise that resolves when the operation is complete.

Example:

javascript
$db.increment('myDatabase', 'myTable', 'score').then((result) => {
  if (result) {
    $log.info('Score incremented by 1');
  } else {
    $log.error('Failed to increment score');
  }
});

Example with value and expiration:

javascript
$db.increment('myDatabase', 'myTable', 'score', 5, 30).then((result) => {
  if (result) {
    $log.info('Score incremented by 5 and will expire in 30 seconds');
  } else {
    $log.error('Failed to increment score');
  }
});

$db.decrement(dbName, tableName, key, value = 1, ttl = 86400)

Description: Decrements the value of a numerical key in the specified table.

Parameters:

  • dbName (string): The name of the database.
  • tableName (string): The name of the table.
  • key (string): The key of the entry to decrement.
  • value (number): The amount to increment by. Number can be integer or float. Default is 1.
  • ttl (number, optional): The time in seconds after which the entry will expire and be automatically deleted. Minimum is 1 second, maximum is 86,400 seconds (24 hours). Default is 86400.

Returns: A promise that resolves when the operation is complete.

Example:

javascript
$db.decrement('myDatabase', 'myTable', 'score', 5).then((result) => {
  if (result) {
    $log.info('Score decremented by 5');
  } else {
    $log.error('Failed to decrement score');
  }
});

Request API

The Request API allows you to send HTTP requests to external URLs.
Maximum response size is 2MB.
Please note, that traffic is also counted towards your project's bandwidth usage.

The following options are available for customizing the requests:

Options:

  • headers: An object containing request headers. Example:
    javascript
    {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer token',
    }
  • timeout: An integer specifying the timeout value in seconds. The maximum allowed timeout is 60 seconds. Default is 10 seconds.
  • auth: An object containing basic authentication credentials. Example:
    javascript
    {
      username: 'myusername',
      password: 'mypassword'
    }

$request.get(url, options)

Description: Sends a GET request to the specified URL.

Parameters:

  • url (string): The URL to send the request to.
  • options (object, optional): Additional options for the request (headers, timeout, etc.).

Returns: A promise that resolves when the operation is complete.

Example:

javascript
$request.get('https://api.example.com/data', {
  headers: {
    'Authorization': 'Bearer token'
  }
}).then(response => {
  $log.info('Response:', response);
}).catch(error => {
  $log.error('Error:', error);
});

$request.post(url, body, options)

Description: Sends a POST request to the specified URL with the given body.

Parameters:

  • url (string): The URL to send the request to.
  • body (object): The body of the request.
  • options (object, optional): Additional options for the request (headers, timeout, etc.).

Returns: A promise that resolves when the operation is complete.

Example:

javascript
$request.post('https://api.example.com/data', {
  key: 'value'
}, {
  headers: {
    'Content-Type': 'application/json'
  }
}).then(response => {
  $log.info('Response:', response);
}).catch(error => {
  $log.error('Error:', error);
});

$request.put(url, body, options)

Description: Sends a PUT request to the specified URL with the given body.

Parameters:

  • url (string): The URL to send the request to.
  • body (object): The body of the request.
  • options (object, optional): Additional options for the request (headers, timeout, etc.).

Returns: A promise that resolves when the operation is complete.

Example:

javascript
$request.put('https://api.example.com/data/1', {
  key: 'newValue'
}, {
  headers: {
    'Content-Type': 'application/json'
  }
}).then(response => {
  $log.info('Response:', response);
}).catch(error => {
  $log.error('Error:', error);
});

$request.patch(url, body, options)

Description: Sends a PATCH request to the specified URL with the given body.

Parameters:

  • url (string): The URL to send the request to.
  • body (object): The body of the request.
  • options (object, optional): Additional options for the request (headers, timeout, etc.).

Returns: A promise that resolves when the operation is complete.

Example:

javascript
$request.patch('https://api.example.com/data/1', {
  key: 'newValue'
}, {
  headers: {
    'Content-Type': 'application/json'
  }
}).then(response => {
  $log.info('Response:', response);
}).catch(error => {
  $log.error('Error:', error);
});

$request.delete(url, options)

Description: Sends a DELETE request to the specified URL.

Parameters:

  • url (string): The URL to send the request to.
  • options (object, optional): Additional options for the request (headers, timeout, etc.).

Returns: A promise that resolves when the operation is complete.

Example:

javascript
$request.delete('https://api.example.com/data/1', {
  headers: {
    'Authorization': 'Bearer token'
  }
}).then(response => {
  $log.info('Response:', response);
}).catch(error => {
  $log.error('Error:', error);
});

In all the examples above, the response object returned by the promise contains the following properties:

  • status (number): The HTTP status code of the response.
  • headers (object): The headers of the response.
  • body (object or string): The body of the response, parsed as JSON if possible, otherwise returned as a string.

If an error occurs during the request, the promise will be rejected with an error object containing details about the error.

Public Files API

The Public Files API allows you to read, write, list, create, delete, rename, and check the existence of files and directories in the public directory of your project.

The public directory is accessible on your domain and can be used to serve static files to clients.

Public Files URL

async $files.public.write(path, content)

Description: Writes content to the specified file path in the public directory.

Parameters:

  • path: The path of the file relative to the public directory.
  • content: The content to write to the file.

Returns: A promise that resolves to true if the write operation is successful, or false otherwise.

Example:

javascript
$files.public.write('/path/to/file.txt', 'Hello, World!').then(result => {
  if (result) {
    $log.info('File written successfully');
  } else {
    $log.error('Failed to write file');
  }
}).catch(error => {
  $log.error('Error writing file:', error);
});

async $files.public.read(path)

Description: Reads content from the specified file path in the public directory.

Parameters:

  • path: The path of the file relative to the public directory.

Returns: A promise that resolves to the content of the file as a string.

Example:

javascript
$files.public.read('/path/to/file.txt').then(content => {
  $log.info('File content:', content);
}).catch(error => {
  $log.error('Error reading file:', error);
});

async $files.public.list(directory)

Description: Lists files and directories in the specified public directory.

Parameters:

  • directory: The public directory to list, relative to the public directory root.

Returns: A promise that resolves to an array of objects representing the items in the directory. Each object has the following properties:

  • name: The name of the file or directory.
  • isDir: A boolean indicating whether the item is a directory (true) or a file (false).
  • size: The size of the file in bytes. This property is only available for files, not directories.

Example:

javascript
$files.public.list('/path/to/public/directory').then(items => {
  $log.info('Directory items:', items);

  for (let item of items) {
    if (item.isDir) {
      $log.info('- Directory:', item.name);
    } else {
      $log.info('- File:', item.name, 'Size:', item.size);
    }
  }
}).catch(error => {
  $log.error('Error listing public directory:', error);
});

async $files.public.createDir(path)

Description: Creates a directory recursively in the public directory.

Parameters:

  • path: The path of the directory to create, relative to the public directory root.

Returns: A promise that resolves to true if the directory is created successfully, or false otherwise.

Example:

javascript
$files.public.createDir('/path/to/new-directory').then(result => {
  if (result) {
    $log.info('Directory created successfully');
  } else {
    $log.error('Failed to create directory');
  }
}).catch(error => {
  $log.error('Error creating directory:', error);
});

async $files.public.isDir(path)

Description: Checks if the specified path in the public directory is a directory.

Parameters:

  • path: The path to check, relative to the public directory root.

Returns: A promise that resolves to true if the path is a directory, or false otherwise.

Example:

javascript
$files.public.isDir('/path/to/directory').then(result => {
  if (result) {
    $log.info('Path is a directory');
  } else {
    $log.info('Path is not a directory');
  }
}).catch(error => {
  $log.error('Error checking directory:', error);
});

async $files.public.delete(path)

Description: Deletes the file or directory at the specified path in the public directory.

Parameters:

  • path: The path of the file or directory to delete, relative to the public directory root.

Returns: A promise that resolves to true if the file or directory is deleted successfully, or false otherwise.

Example:

javascript
$files.public.delete('/path/to/file.txt').then(result => {
  if (result) {
    $log.info('File deleted successfully');
  } else {
    $log.error('Failed to delete file');
  }
}).catch(error => {
  $log.error('Error deleting file:', error);
});

async $files.public.rename(oldPath, newPath)

Description: Renames the file or directory from oldPath to newPath in the public directory.

Parameters:

  • oldPath: The current path of the file or directory, relative to the public directory root.
  • newPath: The new path of the file or directory, relative to the public directory root.

Returns: A promise that resolves to true if the renaming is successful, or false otherwise.

Example:

javascript
$files.public.rename('/path/to/oldFile.txt', '/path/to/newFile.txt').then(result => {
  if (result) {
    $log.info('File renamed successfully');
  } else {
    $log.error('Failed to rename file');
  }
}).catch(error => {
  $log.error('Error renaming file:', error);
});

async $files.public.exists(path)

Description: Checks if a file or directory exists at the specified path in the public directory.

Parameters:

  • path: The path of the file or directory to check, relative to the public directory root.

Returns: A promise that resolves to true if the file or directory exists, or false otherwise.

Example:

javascript
$files.public.exists('/path/to/file.txt').then(result => {
  if (result) {
    $log.info('File exists');
  } else {
    $log.info('File does not exist');
  }
}).catch(error => {
  $log.error('Error checking file existence:', error);
});

Private Files API

The Private Files API allows you to read, write, list, create, delete, rename, and check the existence of files and directories in the private directory of your project.

These files are available only via server-side scripts and are not accessible to clients.

Private Files

async $files.private.write(path, content)

Description: Writes content to the specified file path in the private directory.

Parameters:

  • path: The path of the file relative to the private directory.
  • content: The content to write to the file.

Returns: A promise that resolves to true if the write operation is successful, or false otherwise.

Example:

javascript
$files.private.write('/path/to/file.txt', 'Hello, World!').then(result => {
  if (result) {
    $log.info('File written successfully');
  } else {
    $log.error('Failed to write file');
  }
}).catch(error => {
  $log.error('Error writing file:', error);
});

async $files.private.read(path)

Description: Reads content from the specified file path in the private directory.

Parameters:

  • path: The path of the file relative to the private directory.

Returns: A promise that resolves to the content of the file as a string.

Example:

javascript
$files.private.read('/path/to/file.txt').then(content => {
  $log.info('File content:', content);
}).catch(error => {
  $log.error('Error reading file:', error);
});

async $files.private.list(directory)

Description: Lists files and directories in the specified private directory.

Parameters:

  • directory: The private directory to list, relative to the private directory root.

Returns: A promise that resolves to an array of objects representing the items in the directory. Each object has the following properties:

  • name: The name of the file or directory.
  • isDir: A boolean indicating whether the item is a directory (true) or a file (false).
  • size: The size of the file in bytes. This property is only available for files, not directories.

Example:

javascript
$files.private.list('/path/to/private/directory').then(items => {
  $log.info('Directory items:', items);

  for (let item of items) {
    if (item.isDir) {
      $log.info('- Directory:', item.name);
    } else {
      $log.info('- File:', item.name, 'Size:', item.size);
    }
  }
}).catch(error => {
  $log.error('Error listing private directory:', error);
});

async $files.private.createDir(path)

Description: Creates a directory recursively in the private directory.

Parameters:

  • path: The path of the directory to create, relative to the private directory root.

Returns: A promise that resolves to true if the directory is created successfully, or false otherwise.

Example:

javascript
$files.private.createDir('/path/to/new-directory').then(result => {
  if (result) {
    $log.info('Directory created successfully');
  } else {
    $log.error('Failed to create directory');
  }
}).catch(error => {
  $log.error('Error creating directory:', error);
});

async $files.private.isDir(path)

Description: Checks if the specified path in the private directory is a directory.

Parameters:

  • path: The path to check, relative to the private directory root.

Returns: A promise that resolves to true if the path is a directory, or false otherwise.

Example:

javascript
$files.private.isDir('/path/to/directory').then(result => {
  if (result) {
    $log.info('Path is a directory');
  } else {
    $log.info('Path is not a directory');
  }
}).catch(error => {
  $log.error('Error checking directory:', error);
});

async $files.private.delete(path)

Description: Deletes the file or directory at the specified path in the private directory.

Parameters:

  • path: The path of the file or directory to delete, relative to the private directory root.

Returns: A promise that resolves to true if the file or directory is deleted successfully, or false otherwise.

Example:

javascript
$files.private.delete('/path/to/file.txt').then(result => {
  if (result) {
    $log.info('File deleted successfully');
  } else {
    $log.error('Failed to delete file');
  }
}).catch(error => {
  $log.error('Error deleting file:', error);
});

async $files.private.rename(oldPath, newPath)

Description: Renames the file or directory from oldPath to newPath in the private directory.

Parameters:

  • oldPath: The current path of the file or directory, relative to the private directory root.
  • newPath: The new path of the file or directory, relative to the private directory root.

Returns: A promise that resolves to true if the renaming is successful, or false otherwise.

Example:

javascript
$files.private.rename('/path/to/oldFile.txt', '/path/to/newFile.txt').then(result => {
  if (result) {
    $log.info('File renamed successfully');
  } else {
    $log.error('Failed to rename file');
  }
}).catch(error => {
  $log.error('Error renaming file:', error);
});

async $files.private.exists(path)

Description: Checks if a file or directory exists at the specified path in the private directory.

Parameters:

  • path: The path of the file or directory to check, relative to the private directory root.

Returns: A promise that resolves to true if the file or directory exists, or false otherwise.

Example:

javascript
$files.private.exists('/path/to/file.txt').then(result => {
  if (result) {
    $log.info('File exists');
  } else {
    $log.info('File does not exist');
  }
}).catch(error => {
  $log.error('Error checking file existence:', error);
});