0.1.1 • Published 11 months ago

@simrail-sdk/core v0.1.1

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

SimRail Core SDK

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

This Core SDK module builds on top of an API module (like @simrail-sdk/api) to provide:

  • A more developer-friendly API to prototype with. (where an API module is just about interfacing with SimRail's remote APIs)
  • Live updates on specific resources. (servers, stations, trains)
  • Event subcriptions on resources.
  • Caching of remote API responses.

If you are looking for the SDK module extending on data provided by SimRail's remote APIs, check out wait for the regular SDK module (@simrail-sdk/sdk).

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

Content index

Usage details

Installation

Using NPM:

$ npm i @simrail-sdk/core

or

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

Where VERSION specifies the version to install.

Examples

Simple SDK usage

import Sdk from "@simrail-sdk/core";

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

//
//  Servers
//

// Retrieve a map of Server instances.
const servers = await sdk.servers();

// Retrieve a single Server instance.
const serverCode: Sdk.Server.Code = "en1";
let en1 = servers[serverCode];
// -- or --
en1 = await sdk.server(serverCode);

// Access server data
const isActive = en1.isActive;
const region = en1.region;
// ...

// Update live data (specified in Server.LiveData)
await en1.update();


//
//  Stations
//

// Retrieve a map of Station instances.
let stations = await en1.stations();
// -- or --
stations = await sdk.stations(serverCode);

// Retrieve a single Station instance.
const stationCode: Sdk.Station.Code = "KO";
let katowice = stations[stationCode];
// -- or --
katowice = await en1.station(stationCode);
// -- or --
katowice = await sdk.station(serverCode, stationCode);

// Access station data
const difficultyLevel = katowice.difficultyLevel;
const dispatchers = katowice.dispatchers;
...

// Update live data (specified in Station.LiveData)
await katowice.update();


//
//  Trains
//

// Retrieve a list of active train numbers.
const activeTrains = await en1.activeTrainNumbers();

// Retrieve a single Train instance.
const trainNumber: Sdk.Train.Number = "4144";
let t4144 = await en1.train(trainNumber);
// -- or --
t4144 = await sdk.train(serverCode, trainNumber);

// Access train data
const arrivesAt = t4144.destination.arrivesAt;
const length = t4144.length;
...

// Access live data
const coords = [t4144.liveData.longitude, t4144.liveData.latitude];
const speed = t4144.liveData.speed;
...

Automatic updates and events

import Sdk from "@simrail-sdk/core";

const sdk = new Sdk(...);

const train = await sdk.train("en1", "4144");

//
//  Train live data
//

const liveData = train.liveData;
let liveDataSubscription;
if (liveData.available === true) {

    // Subscribe to live data events.
    liveDataSubscription = liveData.events.subscribe((event) => {

        // Filter events by type.
        switch (event.type) {
            case Sdk.Train.LiveData.Event.Type.AvailableChanged:
                console.log(`Value of "LiveData.available" changed to "${event.available}"!`); break;
            case Sdk.Train.LiveData.Event.Type.DataUpdated:
                console.log(`Value of "LiveData.data" changed to "${JSON.stringify(event.data)}"!`); break;
            case Sdk.Train.LiveData.Event.Type.InPlayableAreaChanged:
                console.log(`Value of "LiveData.inPlayableArea" changed to "${event.inPlayableArea}"!`); break;
        }

    });

    // Specify the update interval and start auto updates.
    liveData.autoUpdateInterval = 10000;
    liveData.autoUpdate = true;

}

// When done, cancel the subscription
liveDataSubscription?.unsubscribe();


//
//  Train timetables
//

// Subscribe to timetable events.
const timetableSubscription = train.timetable.events.subscribe((event) => {
    switch (event.type) {
        case Sdk.Train.Timetable.Event.Type.CurrentChanged:
            console.log(`Value of "Timetable.current" changed! Next train stop: ${event.current.name}`);
    }
});

// Enable live data for some events to be emited.
train.liveData.autoUpdate = true;

// And clean up
timetableSubscription.unsubscribe();

TypeScript strict type checking

To enable strict type checking when using TypeScript, install a Core Setup module like @simrail-sdk/core-setup-pl.

import Sdk from "@simrail-sdk/core";
import { Server, Station, Types } from "@simrail-sdk/core-setup-pl";

// Inject `Types` into the `Sdk` instance to enable strict type checking.
const sdk = new Sdk<Types>(...);

const en1 = sdk.server(Server.Code.EN1);
const en2 = sdk.server("en2");

const będzin     = sdk.station("en1", Station.Code.B);
const düsseldorf = sdk.station("en1", "Dü"); // <-- Fails because Düsseldorf doesn't exist.
const katowice   = sdk.station("en1", "KO");

const train4144 = sdk.train("en1", "4144");
const train4145 = sdk.train("en1", "4145"); // <-- Fails because 4145 doesn't exist.

// Obtaining a list of server/station codes:
const serverCodes  = Object.values(Server.Code);
const stationCodes = Object.values(Station.Code);

Working with result caching

import Sdk from "@simrail-sdk/core";

// Cache configuration can be specified at SDK class construction.
const sdk = new Sdk({
    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  },
            },
        },

        ...

    },
});


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

Providing a (custom) API or Core API class

import CoreApi from "@simrail-sdk/api-core-node";
import Api from "@simrail-sdk/api";
import Sdk from "@simrail-sdk/core";

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

// Or alternatively, to provide a different *Core API* class, include this in the API config.
const coreApi = new CoreApi(...);
const api     = new Api({ core: coreApi }); // <-- Inject Core API here
const sdk     = new Sdk({ api: api });      // <-- Inject API here

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/core: @simrail-sdk/core "View module \"@simrail-sdk/core\"" api-reference-common: common "View module \"common\"" api-reference-common/index.d.ts: common/index.d.ts "View module \"common/index.d.ts\"" api-reference-common/index.ts: common/index.ts "View module \"common/index.ts\"" 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/index.d.ts: node_modules/@simrail-sdk/api/index.d.ts "View module \"node_modules/@simrail-sdk/api/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-line/index.ts: line/index.ts "View module \"line/index.ts\"" api-reference-server/index.ts: server/index.ts "View module \"server/index.ts\"" api-reference-train/index.ts: train/index.ts "View module \"train/index.ts\"" api-reference-train/liveData/index.ts: train/liveData/index.ts "View module \"train/liveData/index.ts\"" api-reference-station/index.ts: station/index.ts "View module \"station/index.ts\"" api-reference-train/timetable/index.ts: train/timetable/index.ts "View module \"train/timetable/index.ts\"" api-reference-train/timetable/entry/index.ts: train/timetable/entry/index.ts "View module \"train/timetable/entry/index.ts\"" api-reference-track/index.ts: track/index.ts "View module \"track/index.ts\"" api-reference-index.ts: index.ts "View module \"index.ts\"" api-reference-line: line "View module \"line\"" api-reference-line/index.d.ts: line/index.d.ts "View module \"line/index.d.ts\"" api-reference-server: server "View module \"server\"" api-reference-server/index.d.ts: server/index.d.ts "View module \"server/index.d.ts\"" api-reference-station: station "View module \"station\"" api-reference-station/index.d.ts: station/index.d.ts "View module \"station/index.d.ts\"" api-reference-track: track "View module \"track\"" api-reference-track/index.d.ts: track/index.d.ts "View module \"track/index.d.ts\"" api-reference-train: train "View module \"train\"" api-reference-train/index.d.ts: train/index.d.ts "View module \"train/index.d.ts\"" api-reference-train/liveData: train/liveData "View module \"train/liveData\"" api-reference-train/liveData/index.d.ts: train/liveData/index.d.ts "View module \"train/liveData/index.d.ts\"" api-reference-train/timetable/entry: train/timetable/entry "View module \"train/timetable/entry\"" api-reference-train/timetable/entry/index.d.ts: train/timetable/entry/index.d.ts "View module \"train/timetable/entry/index.d.ts\"" api-reference-train/timetable: train/timetable "View module \"train/timetable\"" api-reference-train/timetable/index.d.ts: train/timetable/index.d.ts "View module \"train/timetable/index.d.ts\""

class Entry   

Implements:  Data

Type params:ExtendsOptionalDefault
TypesEntry.TypesNoN/A
EntryTypeEntry.TypeYesEntry.Type

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:23

new Entry.constructor(config)   

Type params:ExtendsOptionalDefault
TypesTypes<Types>NoN/A
EntryTypeTypeYesType
Arguments:Type
configConfig<Types | EntryType>

Returns:  Entry<Types | EntryType>

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:97

property Entry.data   

read-only

Type:  Data<EntryType>

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:27

property Entry.timetable   

read-only

Type:  Timetable<Types>

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:25

property Entry.arrivesAt   

read-only

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:29

property Entry.departsAt   

read-only

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:33

property Entry.first   

read-only

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:37

property Entry.index   

read-only

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:41

property Entry.kilometrage   

read-only

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:45

property Entry.last   

read-only

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:49

property Entry.line   

read-only

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:53

property Entry.localTrack   

read-only

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:57

property Entry.maxSpeed   

read-only

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:61

property Entry.name   

read-only

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:65

property Entry.platform   

read-only

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:69

property Entry.pointId   

read-only

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:73

property Entry.radioChannels   

read-only

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:77

property Entry.stationCategory   

read-only

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:81

property Entry.supervisedBy   

read-only

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:85

property Entry.trainType   

read-only

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:89

property Entry.type   

read-only

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:93

method Entry.next()   

Returns:  undefined | Entry<Types | Type>

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:102

method Entry.previous()   

Returns:  undefined | Entry<Types | Type>

Since: 0.1.0

Definition:  train/timetable/entry/index.ts:108

class LiveData   

Specifies live data of a train.

See LiveData.get() for an awaitable constructor method.

Implements:  Data

Type params:ExtendsDescription
TypesLiveData.Train.TypesType information about the LiveData and SDK.

Since: 0.1.0

Definition:  train/liveData/index.ts:36

new LiveData.constructor(config, callback)   

Type params:Extends
TypesTypes<string | string | string | string | Types>
Arguments:Type
configConfig<Types>
callbackCallback<Types>

Returns:  LiveData<Types>

Since: 0.1.0

Definition:  train/liveData/index.ts:214

property LiveData.events   

read-only

Specifies a live data event emitter.

Type:  Emitter<Types>

Since: 0.1.0

Definition:  train/liveData/index.ts:39

property LiveData.sdk   

read-only

Specifies a reference to the Sdk class instance.

Type:  Sdk<Types>

Since: 0.1.0

Definition:  train/liveData/index.ts:42

property LiveData.train   

read-only

Specifies a reference to the Train the live data belongs to.

Type:  Train<Types>

Since: 0.1.0

Definition:  train/liveData/index.ts:45

property LiveData.autoUpdateapi-reference-train/liveData/index.ts~LiveData.au

0.1.1

11 months ago