0.1.1 • Published 12 months ago

@simrail-sdk/api v0.1.1

Weekly downloads
-
License
See LICENSE.md
Repository
github
Last release
12 months ago

SimRail API SDK

This is a simple SDK (community edition) for interacting with the SimRail APIs.

This API module builds a layer on top of a Core API module (like @simrail-sdk/api-core-node) by providing:

  • Methods to request single resources. (A single server, station or train)
  • Automatic pulling of remote data updates.
  • Update event subcriptions.
  • Caching of remote API responses.

This API module is only about interacting with SimRail's remote APIs. If you are looking for a more developer-friendly SDK, checkout:

This module requires the use of a Core API module to be able to extend it. By default this module will use @simrail-sdk/api-core-node. To provide another Core API module or a custom one, check out the example providing a (custom) Core API class below.

Content index

Usage details

Installation

Using NPM:

$ npm i @simrail-sdk/api

or

$ npm i github:simrail-sdk/api#VERSION

Where VERSION specifies the version to install.

Examples

Simple API usage

import Api from "@simrail-sdk/api";

const api = new Api({
    endpoints: {
        liveData: "https://panel.simrail.eu:8084",
        timetable: "https://api1.aws.simrail.eu:8082/api",
    },
});
const serverCode: Api.ServerCode = "en1";

api.getActiveServers().then(...);
api.getActiveServer(serverCode).then(...);
// {
//     id: "638fec40d089346098624eb5",
//     isActive: true,
//     serverCode: "en1",
//     serverName: "EN1 (English)",
//     serverRegion: "Europe",
// },

api.getActiveStations(serverCode).then(...);
api.getActiveStation(serverCode, "KO").then(...);
// {
//     additionalImage1URL: "https://api.simrail.eu:8083/Thumbnails/Stations/ko2.jpg",
//     additionalImage2URL: "https://api.simrail.eu:8083/Thumbnails/Stations/ko3.jpg",
//     difficultyLevel: 5,
//     dispatchedBy: [],
//     id: "644133f3858f72cc3d476e42",
//     latitude: 50.25686264038086,
//     longitude: 19.01921844482422,
//     mainImageURL: "https://api.simrail.eu:8083/Thumbnails/Stations/ko1m.jpg",
//     name: "Katowice",
//     prefix: "KO"
// },

api.getActiveTrains(serverCode).then(...);
api.getActiveTrain(serverCode, "446004").then(...);
// {
//     endStation: "Częstochowa",
//     id: "662f96b3766d379b4f3f525f",
//     runId: "73c0f0ea-20d9-4317-8339-8bc7d098bd35",
//     serverCode: "en1",
//     startStation: "Jaworzno Szczakowa",
//     trainData: {
//     inBorderStationArea: true,
//     latitude: 50.262142181396484,
//     longitude: 19.269641876220703,
//     vdDelayedTimetableIndex: 1,
//     velocity: 40,
//     distanceToSignalInFront: 386.6281433105469,
//     signalInFront: "SMA_G@7129,82510,8",
//     signalInFrontSpeed: 40
//     },
//     trainName: "PWJ",
//     trainNoLocal: "446004",
//     type: "bot",
//     vehicles: [ "EN57/EN57-1003", "EN57/EN57-614", "EN57/EN57-1755" ]
// },

api.getTimetable(serverCode).then(...);
api.getTimetable(serverCode, "446004").then(...);
// {
//     endStation: "Częstochowa",
//     endsAt: "03:53:00",
//     locoType: "EN57 (5B+6B+5B)",
//     runId: "73c0f0ea-20d9-4317-8339-8bc7d098bd35",
//     startStation: "Jaworzno Szczakowa",
//     startsAt: "02:15:00",
//     timetable: [
//       {
//         departureTime: "2024-08-05 02:15:00",
//         displayedTrainNumber: "446004",
//         line: 133,
//         maxSpeed: 100,
//         kilometrage: 15.81,
//         nameForPerson: "Jaworzno Szczakowa",
//         nameOfPoint: "Jaworzno Szczakowa",
//         pointId: "1472",
//         stopType: "NoStopOver",
//         trainType: "PWJ",
//         supervisedBy: "Jaworzno Szczakowa"
//       },
//       ...
//     ],
//     trainLength: 60,
//     trainName: "PWJ",
//     trainNoLocal: "446004",
//     trainWeight: 60
// }

Automatic updates

import Api from "@simrail-sdk/api";

const api = new Api(...);
const serverCode: Api.ServerCode = "en1";

// Start auto updates using data from "en1".
api.startAutoUpdates(serverCode);

// Stop auto updates.
api.stopAutoUpdates();

// Restart auto updates.
api.startAutoUpdates();

// Or, do the same thing using accessors
api.autoUpdateServer = serverCode;
api.autoUpdate = true;
const updatesEnabled = api.autoUpdate;

Handling events

import Api from "@simrail-sdk/api";

const api = new Api(...);

// Subscribe to API events.
const eventSubscription = api.events.subscribe((event) => {
    switch (event.type) {
        case Api.Event.Type.ActiveServersUpdated:  event.activeServers[0].id;       break;
        case Api.Event.Type.ActiveStationsUpdated: event.activeStations[0].code;    break;
        case Api.Event.Type.ActiveTrainsUpdated:   event.activeTrains[0].id;        break;
        case Api.Event.Type.AutoUpdateChanged:     event.autoUpdate === true;       break;
        case Api.Event.Type.TimetableUpdated:      event.timetable[0].trainNoLocal; break;
    }
});

// Unsubscribe from events.
eventSubscription.unsubscribe();

Working with result caching

import Api from "@simrail-sdk/api";

// Cache configuration can be specified at API class construction.
const api = new Api({

    /** Specifies a config for requests to the timetable endpoint. */
    timetable: {
        cache: {
            /**
             * Specifies if caching is enabled.
             * @default true
             */
            enabled: true,
            /**
             * Specifies for how long a timetable record is cached in seconds.
             * This value also specifies the update interval for auto updates.
             * @default 1440
             */
            retention: 1440,
            /**
             * Specifies if only one timetable record should be cached.
             *
             * When set to:
             * - `true` only the last timetable record will be cached.
             * - `false` a timetable record will be cached for
             *   each server that was queried for a timetable.
             *   Use this when you are actively querying multiple servers.
             *
             * @default true
             */
            singleRecordOnly: true,
        },
    },

    /** Specifies a config for requests to the live data endpoint. */
    liveData: {
        cache: {
            // Values displayed are the defaults.
            activeServers:  { enabled: true, retention: 30 },
            activeStations: { enabled: true, retention: 30 },
            activeTrains:   { enabled: true, retention: 5  },
        },
    },

    ...

});


// Independent of the cache config you can prevent a cached result
//   to be returned by specifying the `noCache` argument.
const serverCode: Api.ServerCode = "de1";
const noCache: Api.NoCache = true;
const nonCachedServers        = await api.getActiveServers(noCache);
const nonCachedServer         = await api.getActiveServer(serverCode, noCache);
const nonCachedStations       = await api.getActiveStations(serverCode, noCache);
const nonCachedStation        = await api.getActiveStation(serverCode, "KO", noCache);
const nonCachedTrains         = await api.getActiveTrains(serverCode, noCache);
const nonCachedTrain          = await api.getActiveTrain(serverCode, "446004", noCache);
const nonCachedTimetable      = await api.getTimetable(serverCode, noCache);
const nonCachedTrainTimetable = await api.getTimetable(serverCode, "446004", noCache);


// If you need to, flush cached data.
api.flushCache();
// Or
api.flushActiveServerCache();
api.flushActiveStationCache();
api.flushActiveTrainCache();
api.flushTimetableCache();

Providing a (custom) Core API class

import Api from "@simrail-sdk/api";
import Core from "different-api-core";

// By default the API will use the Core API class from package `@simrail-sdk/api-core-node`.
// To provide another Core API class or a custom one, just include the instance in the API config.
const core = new Core({ endpoints });
const api = new Api({ core });

API reference

NOTE: The API reference section doesn't account for namespaces, this unfortunately means the documentation below is not entirely complete. Please investigate the TypeScript definition files for the full API.

api-reference-@simrail-sdk/api: @simrail-sdk/api "View module \"@simrail-sdk/api\"" api-reference-index: index "View module \"index\"" api-reference-index.d.ts: index.d.ts "View module \"index.d.ts\"" api-reference-node_modules/@simrail-sdk/api-core-node/index.d.ts: node_modules/@simrail-sdk/api-core-node/index.d.ts "View module \"node_modules/@simrail-sdk/api-core-node/index.d.ts\"" api-reference-node_modules/@simrail-sdk/api-core-node/types/liveData/index.d.ts: node_modules/@simrail-sdk/api-core-node/types/liveData/index.d.ts "View module \"node_modules/@simrail-sdk/api-core-node/types/liveData/index.d.ts\"" api-reference-node_modules/@simrail-sdk/api-core-node/types/timetable/index.d.ts: node_modules/@simrail-sdk/api-core-node/types/timetable/index.d.ts "View module \"node_modules/@simrail-sdk/api-core-node/types/timetable/index.d.ts\"" api-reference-index.ts: index.ts "View module \"index.ts\""

class Api   

Specifies an API class instance for interacting with SimRail's remote API.

Implements:  Omit<Api.Core, "config">

Since: 0.1.0

Definition:  index.ts:29

new Api.constructor(config)   

Arguments:Type
configConfig

Returns:  Api

Since: 0.1.0

Definition:  index.ts:94

property Api.autoUpdateServer   

optional

Specifies the unique code of the server to automatically retrieve data from.

Type:  string

Since: 0.1.0

Definition:  index.ts:47

property Api.config   

read-only

Specifies the configuration of the API.

Type:  Config

Since: 0.1.0

Definition:  index.ts:35

property Api.core   

read-only

Specifies a reference to the Core API.

Type:  Api.Core

Since: 0.1.0

Definition:  index.ts:32

property Api.events   

read-only

Specifies the event emitter for API events.

Type:  Emitter

Since: 0.1.0

Definition:  index.ts:38

property Api.autoUpdate   

Since: 0.1.0

Definition:  index.ts:73

method Api.flushActiveServerCache()   

Method to flush all cached active server records.

Returns:  Api  - This API instance.

Since: 0.1.0

Definition:  index.ts:109

method Api.flushActiveStationCache()   

Method to flush all cached active station records.

Returns:  Api  - This API instance.

Since: 0.1.0

Definition:  index.ts:119

method Api.flushActiveTrainCache()   

Method to flush all cached active train records.

Returns:  Api  - This API instance.

Since: 0.1.0

Definition:  index.ts:129

method Api.flushCache()   

Method to flush all cached records.

Returns:  Api  - This API instance.

Since: 0.1.0

Definition:  index.ts:139

method Api.flushTimetableCache()   

Method to flush all cached timetable records.

Returns:  Api  - This API instance.

Since: 0.1.0

Definition:  index.ts:152

method Api.getActiveServer(serverCode, noCache)   

Method to retrieve an active server from the live data endpoint.

Arguments:TypeOptionalDefaultDescription
serverCodestringNoN/AThe unique code of the server.
noCachebooleanYesfalsePrevent returning a cached result.

Returns:  Promise<Server>  - The multiplayer server.

Since: 0.1.0

Definition:  index.ts:164

method Api.getActiveServers(noCache)   

Method to retrieve active servers from the live data endpoint.

Arguments:TypeOptionalDefaultDescription
noCachebooleanYesfalsePrevent returning a cached result.

Returns:  Promise<Server[]>  - A list of multiplayer servers.

Since: 0.1.0

Definition:  index.ts:178

method Api.getActiveStation(serverCode, stationCode, noCache)   

Method to retrieve an active dispatch station from the live data endpoint.

The value for stationCode can be either:

  • The prefix of the station.
  • The code which is the prefix but stripped from diacritics. Example: prefix ŁA equals code LA.
Arguments:TypeOptionalDefaultDescription
serverCodestringNoN/AThe code of the related server.
stationCodestringNoN/AThe unique code of the dispatch station.
noCachebooleanYesfalsePrevent returning a cached result.

Returns:  Promise<Station>  - The active dispatch station.

Since: 0.1.0

Definition:  index.ts:210

method Api.getActiveStations(serverCode, noCache)   

Method to retrieve active dispatch stations from the live data endpoint.

Arguments:TypeOptionalDefaultDescription
serverCodestringNoN/AThe unique code of the multiplayer server.
noCachebooleanYesfalsePrevent returning a cached result.

Returns:  Promise<Station[]>  - A list of active dispatch stations.

Since: 0.1.0

Definition:  index.ts:225

method Api.getActiveTrain(serverCode, trainNoLocal, noCache)   

Method to retrieve an active train from the live data endpoint.

Arguments:TypeOptionalDefaultDescription
serverCodestringNoN/AThe code of the related server.
trainNoLocalstringNoN/AThe national number of the train.
noCachebooleanYesfalsePrevent returning a cached result.

Returns:  Promise<Train>  - The active dispatch train.

Since: 0.1.0

Definition:  index.ts:257

method Api.getActiveTrains(serverCode, noCache)   

Method to retrieve active trains from the live data endpoint.

Arguments:TypeOptionalDefaultDescription
serverCodestringNoN/AThe unique code of the multiplayer server.
noCachebooleanYesfalsePrevent returning a cached result.

Returns:  Promise<Train[]>  - A list of active trains.

Since: 0.1.0

Definition:  index.ts:272

method Api.getTimetable(serverCode, noCache)   

Method to retrieve timetable data from the timetable endpoint.

Arguments:TypeOptionalDescription
serverCodestringNoThe unique code of the multiplayer server.
noCachebooleanYes

Returns:  Promise<Data[]>

Since: 0.1.0

Definition:  index.ts:297

method Api.getTimetable(serverCode, trainNoLocal, noCache)   

Arguments:TypeOptional
serverCodestringNo
trainNoLocalstringNo
noCachebooleanYes

Returns:  Promise<Data>

Since: 0.1.0

Definition:  index.ts:297

method Api.getTimetable(serverCode, trainNoOrNoCache, noCache)   

Arguments:TypeOptional
serverCodestringNo
trainNoOrNoCachestringYes
noCachebooleanYes

Returns:  Promise<Data | Data[]>

Since: 0.1.0

Definition:  index.ts:297

method Api.startAutoUpdates(autoUpdateServer)   

Method to start auto updating cached data.

This will update cached data and enable events. The update interval is determined by checking the cache retention value.

NOTE: Auto update only works for records which have caching enabled.

Arguments:TypeOptional
autoUpdateServerstringYes

Returns:  Api  - This Api instance.

Since: 0.1.0

Definition:  index.ts:337

method Api.stopAutoUpdates()   

Method to stop auto updating cached data.

Returns:  Api  - This Api instance.

Since: 0.1.0

Definition:  index.ts:381

const DEFAULT_ACTIVE_SERVER_RETENTION   

Specifies the default retention for active server records.

Type:  Config.LiveData.Cache.ActiveServers.Retention

Since: 0.1.0

Definition:  index.ts:441

const DEFAULT_ACTIVE_STATION_RETENTION   

Specifies the default retention for active station records.

Type:  Config.LiveData.Cache.ActiveStations.Retention

Since: 0.1.0

Definition:  index.ts:443

const DEFAULT_ACTIVE_TRAIN_RETENTION   

Specifies the default retention for active train records.

Type:  Config.LiveData.Cache.ActiveTrains.Retention

Since: 0.1.0

Definition:  index.ts:445

const DEFAULT_TIMETABLE_RETENTION   

Specifies the default retention for timetable records.

Type:  Config.Timetable.Cache.Retention

Since: 0.1.0

Definition:  index.ts:447

const VERSION   

Specifies the version of the API.

Type:  Version

Since: 0.1.0

Definition:  index.ts:432

const VMAX   

Specifies the maximum allowable operating speed. (Vmax)

Type:  "vmax"

Since: 0.1.0

Definition:  node_modules/@simrail-sdk/api-core-node/types/liveData/index.d.ts:15

const VMAX_VALUE   

Specifies the "speed" value that will indicate "vmax".

Type:  32767

Since: 0.1.0

Definition:  node_modules/@simrail-sdk/api-core-node/types/liveData/index.d.ts:18

enum Type   

Specifies a type of API event.

Since: 0.1.0

Definition:  index.ts:700

member Type.ActiveServersUpdated   

Specifies an event that fires when cached active servers updated.

Type:  "activeServersUpdated"

Since: 0.1.0

Definition:  index.ts:704

member Type.ActiveStationsUpdated   

Specifies an event that fires when cached active dispatch stations updated.

Type:  "activeStationsUpdated"

Since: 0.1.0

Definition:  index.ts:706

member Type.ActiveTrainsUpdated   

Specifies an event that fires when cached active trains updated.

Type:  "activeTrainsUpdated"

Since: 0.1.0

Definition:  index.ts:708

member Type.AutoUpdateChanged   

Specifies an event that fires when the value of Api.autoUpdate changes.

Type:  "autoUpdateChanged"

Since: 0.1.0

Definition:  index.ts:702

member Type.TimetableUpdated   

Specifies an event that fires when cached timetable data updated.

Type:  "timetableUpdated"

Since: 0.1.0

Definition:  index.ts:710

interface ActiveServer   

Extends:  Server

Since: 0.1.0

Definition:  index.ts:623

interface ActiveServers   

Since: 0.1.0

Definition:  index.ts:625

property ActiveServers.map   

Type:  Map

Since: 0.1.0

Definition:  index.ts:626

property ActiveServers.timestamp   

Type:  number

Since: 0.1.0

Definition:  index.ts:627

interface ActiveServersUpdated   

Specifies an event that fires when cached active servers updated.

Extends:  Base<Type.ActiveServersUpdated>

Since: 0.1.0

Definition:  index.ts:729

property ActiveServersUpdated.activeServers   

Type:  Server[]

Since: 0.1.0

Definition:  index.ts:730

interface ActiveStation   

Extends:  Station

Since: 0.1.0

Definition:  index.ts:635

property ActiveStation.code   

Type:  string

Since: 0.1.0

Definition:  index.ts:636

interface ActiveStationsUpdated   

Specifies an event that fires when cached active dispatch stations updated.

Extends:  Base<Type.ActiveStationsUpdated>

Since: 0.1.0

Definition:  index.ts:734

property ActiveStationsUpdated.activeStations   

Type:  List

Since: 0.1.0

Definition:  index.ts:735

interface ActiveTrain   

Extends:  Train

Since: 0.1.0

Definition:  index.ts:654

interface ActiveTrainsUpdated   

Specifies an event that fires when cached active trains updated.

Extends:  Base<Type.ActiveTrainsUpdated>

Since: 0.1.0

Definition:  index.ts:739

property ActiveTrainsUpdated.activeTrains   

Type:  Train[]

Since: 0.1.0

Definition:  index.ts:740

interface AutoUpdateChanged   

Specifies an event that fires when the value of Api.autoUpdate changes.

Extends:  Base<Type.AutoUpdateChanged>

Since: 0.1.0

Definition:  index.ts:724

property AutoUpdateChanged.autoUpdate   

Type:  boolean

Since: 0.1.0

Definition:  index.ts:725

interface Base   

Type params:Extends
EventTypeType

Since: 0.1.0

Definition:  index.ts:713

Extended by

property Base.api   

Specifies a reference to the related Api instance.

Type:  Api

Since: 0.1.0

Definition:  index.ts:715

property Base.type   

Specifies the type of API event.

Type:  EventType

Since: 0.1.0

Definition:  [index.

0.1.1

12 months ago

0.1.0

12 months ago