Socket
Socket
Sign inDemoInstall

syshub-rest-module

Package Overview
Dependencies
Maintainers
1
Versions
48
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

syshub-rest-module

This package provides a generic library for the communication from an Angular SPA with a NT-Ware uniFLOW sysHUB backend server based on HTTPS Rest API with OAuth2 flow.


Version published
Weekly downloads
2
Maintainers
1
Weekly downloads
 
Created
Source

Syshub Rest Module

This package provides a generic library for the communication from an Angular SPA with a NT-Ware uniFLOW sysHUB backend server based on HTTPS Rest API with OAuth2 flow. The contained Rest Service provides methods for login and logout-functionality and an automatic token refresh. Furthermore you can use the get- and post-methods to send a request to any sysHUB Rest API endpoint. The package contains anything needed for the communication, just at it as a provider to your application and provide it with settings like hostname and credentials.

Install

Run npm i syshub-rest-module in your project root to add this library as dependency.

Setup configuration

After installing the module, create a configuration for the credentials, for example in your environment.ts file. If there is no environment.ts yet, see this article on StackOverflow. Make sure that the environment variable implements the Env interface so that type checking prevents errors already during the development of the app.

import { Env } from "syshub-rest-module";
import { SyshubVersion } from 'syshub-rest-module';

export const environment: Env = {
    syshub: {
        host: "http://localhost:8088/",
        version: SyshubVersion.sysHUB_2022,
        basic: {
            enabled: false,
            username: "foo",
            password: "foo!bar",
            provider: "<syshubApiserverName>",
        },
        oauth: {
            enabled: true,
            clientId: "<syshubAuthserverClientId>",
            clientSecret: "<syshubAuthserverClientSecret>",
        }
    }
};

Make sure to enable either basic auth or oauth. Basic auth requires an authentication provider that you must set up in API Server configuration. This is not required for OAuth authentication. For a detailed explanation of the configuration values see chapter Configuration.

A short note on sysHUB 2021 server

The Rest API had a huge change from 2021 to 2022 version of the server. The API is now available in the url path /webapi/ instead of the old /cosmos-webapi/. Therefore this module contains a version switch in the configuration. If the switch is not set, it will always use the latest version, currently 2022. In order to use the module with an old 2021 server change the version accordingly.

In your app.module.ts add the following three providers:

import { RestService, RestSettings, Settings, SyshubInterceptor } from 'syshub-rest-module';

...

providers: [
    { provide: Settings, multi: false, useValue: new Settings(<RestSettings>(environment.syshub)) },
    { provide: RestService, multi: false, deps: [Settings, HttpClient] },
    { provide: HTTP_INTERCEPTORS, multi: true, useClass: SyshubInterceptor, deps: [Settings, RestService] }
  ],

The Settings-provider requires an initialized object of type Settings, where the constructor expects an object that implements the RestSettings interface. For an example, see above the environment.syshub object in the Install/Setup configuration chapter.

Usage

In any component you require access to the REST API import the RestService:

import { RestService } from 'syshub-rest-module';

Userlogin

Within your components you are now able to access all service methods and properties. For example:

import { RestService } from 'syshub-rest-module';

...

export class AppComponent {

    ...

    constructor(private restService: RestService) {}

    ...

    sendLogin(): void {
        this.restService.login(this.username, this.password).subscribe((response) => {
            console.log(response)
            if (response == null) // initial status
                return;
            if (response === true) {
                // login successfull
            }
            else {
                // login failed
            }
        });
    }

    ...

}

Calling Rest API endpoints

With version 2.0 of this module we started adding lots of methods to the Rest service to call designated endpoints like method getCurrentUser() to call the endpoint /webapi/v2/currentUser. A documentation of this methods is at the end of this document in chapter Implemented endpoint methods.

Whenever possible use this methods. If your require a call to a different Rest API endpoint that is not available as a method use one of the following generic methods for Http GET, POST, etc instead.

Rest API GET

To send an HTTP GET to the Rest API use get() method from the RestService, for example:

this.restService.get('currentUser').subscribe((response) => {
    if (response.status == HttpStatusCode.Ok) {
        // Ok response
        // Rest API endpoint may return a different status, check Swagger UI to know which status to check for
      } else {
        //Failed response 
        
      }
});

In case of OAuth Authentication: make sure the user is already logged in (subscribe to RestService.isLoggedIn or call RestService.getIsLoggedIn()). If user is not yet loggedin the endpoint will return HTTP Status code 401 (Unauthorized).

Rest API POST

To send an HTTP POST to the Rest API use post() method from the RestService, for example:

this.restService.post('jobs', myJobObject).subscribe((response) => {
    if (response.status == HttpStatusCode.Ok) {
        // Ok response
        // Rest API endpoint may return a different status, check Swagger UI to know which status to check for
      } else {
        //Failed response 
        
      }
});

In case of OAuth Authentication: make sure the user is already logged in (subscribe to RestService.isLoggedIn or call RestService.getIsLoggedIn()). If user is not yet loggedin the endpoint will return HTTP Status code 401 (Unauthorized). Also make sure that your provided object matches the definition from sysHUB as you can find it in the Swagger UI.

Rest API DELETE, PATCH and PUT

The sysHUB Rest API also expects the HTTP methods Delete, Patch or Put depending on the endpoint. Therefore the RestService provides those methods too: RestService.delete(), RestService.patch() and RestService.put(). As they are work almost identically to the Get and Post methods, there's no separate usage guide here. Just replace RestService.get() with RestService.delete() to call a Delete-Endpoint. Replace RestService.post() with RestService.patch() or RestService.put() to call the Patch and Put endpoints. The later ones also expect an object to be sent to the Webserver.

Configuration

The configuration of the RestService is done with a Settings object which requires a RestSettings object. The later one can easily be created within the environments-files or at runtime (see Install and Usage). The RestSettings object must have basic or oauth enabled and may allow some other values:

  • host: Required (type string Url); Url to the sysHUB Webserer root, like http://localhost:8088/.
  • version: Optional, required for sysHUB 2021 server; Pick one value from the enum:
    • SyshubVersion.sysHUB_2021
    • SyshubVersion.sysHUB_2022
    • SyshubVersion.DEFAULT which is the same as SyshubVersion.sysHUB_2022
  • basic: Optional, required for basic authentication (type object)
    • enabled: Required (type boolean); true if basic auth to be enabled, default false.
    • username: Optional, required for basic authentication (type string)
    • password: Optional, required for basic authentication (type string)
    • provider: Optional, required for basic authentication (type string); The name of the Api server provider from the sysHUB configuration
  • oauth: Optional, required for OAuth (type object)
    • enabled: Required (type boolean); true if OAuth to be enabled, default false.
    • clientId: Optional, required for OAuth (type string); The name of the Auth server client
    • clientSecret: Optional, required for OAuth (type string); The name of the Auth server client secret
    • scope: Optional (type string); The scope as defined in the sysHUB Auth server, replace ; with +. Allowed values: private, public, private+public or public+private, Default: public
    • storeKey: Optional (type string); The name that is used to store the credentials in the local browser cache, Default: authmod-session
  • options: Optional (type object)
    • autoConnect, Optional (type boolean), Not yet implemented
    • autoLogoutOn401, Optional (type boolean), If the sysHUB Rest API returns HTTP Status 401, this property causes the Rest Service to remove the users session information from the browser cache, Default: true
    • autoLogoutTimer, Optional (type boolean), Not yet implemented

Implemented endpoint methods

The following methods provide a type-checked shorthand for the generic get()/post()/... implementation and also convert the default sysHUB response into a specialized one (eg. the console command MEM returns just a string[] which is converted into an object with meaningfull names and values). If the endpoint requires any payload, the specialized methods do expect this payload with a predefined interface to make sure you provide all the necessary information when calling it. Whenever possible use this methods instead of get() or the other ones.

backupSyshub(string, string, string, string[])

This method calls the POST endpoint /webapi/v3/backuprestore/backup?folder=....

  • Payload:
    • Param 1: string backupName Name for this backup.
    • Param 1: string backupDescription Description text for this backup.
    • Param 1: string folderpath Backup folder that will be created inside sysHUB root folder.
    • Param 1: string[] includeOptions Array of options to backup. You can use the enum SyshubBackupTypesEnum provided with this module. This enum contains all available Options that may be used with this endpoint (Usage: Object.keys(SyshubBackupTypesEnum).filter((item) => isNaN(Number(item))) to create a string[] of all available objects).
  • Returns: SyshubResponseSimple

getBackupMetadata(string)

This method calls the POST endpoint /webapi/v3/backuprestore/metadata?folder=....

  • Payload:
    • Param 1: string folderpath Backup folder that will be created inside sysHUB root folder.
  • Returns: SyshubBackupMeta

getCertStoreItems('keystore'|'truststore')

This method calls the GET endpoint /webapi/v3/certificate/list/....

  • Payload:
    • Param 1: store: 'keystore' | 'truststore'
  • Returns: SyshubCertStoreItem

getCurrentUser()

This method calls the GET endpoint /webapi/v3/currentUser.

  • Payload: None.
  • Returns: SyshubUserAccount

getServerInformation()

This method calls the GET endpoint /webapi/v3/server/list/information.

  • Payload: None.
  • Returns: SyshubServerInformation

getServerProperties()

This method calls the GET endpoint /webapi/v3/server/properties.

  • Payload: None.
  • Returns: { [key: string]: string }

getWorkflowExecution()

This method calls the GET endpoint /webapi/v3/workflows/execute?uuid=... and returns a list of running workflow executions started via Rest API and matching the given uuid param.

  • Payload: None.
  • Returns: SyshubWorkflowExecution[]; Be aware that the documentation states the endpoint returns an SyshubWorkflowExecution object although in sysHUB 2022 and 2023 it returns an array with one object inside (if uuid is found). This may change in upcoming versions to match the documentation.

getWorkflowExecutions()

This method calls the GET endpoint /webapi/v3/workflows/execute and returns a list of running workflow executions started via Rest API.

  • Payload: None.
  • Returns: SyshubWorkflowExecution[]

restoreSyshub(string, string[])

This method calls the POST endpoint /webapi/v3/backuprestore/restore?folder=....

  • Payload:
    • Param 1: string folderpath Backup folder that will be created inside sysHUB root folder.
    • Param 1: string[] includeOptions Array of options to backup. You can use the enum SyshubBackupTypesEnum provided with this module. This enum contains all available Options that may be used with this endpoint (Usage: Object.keys(SyshubBackupTypesEnum).filter((item) => isNaN(Number(item))) to create a string[] of all available objects).
  • Returns: SyshubResponseSimple

runConsoleCommand(string, string[])

This method calls the POST endpoint /webapi/v3/consolecommands/execute/....

  • Payload:
    • Param 1: cmd: string The command to execute
    • Param 2: params: string[] = [] An array of parameters to send along with the command
  • Returns: string[]

You may use one of the specialiced methods to get the string[] converted to a javascript object.

runConsoleCommandHelp()

This method calls the POST endpoint /webapi/v3/consolecommands/execute/HELP.

  • Payload: None
  • Returns: { [key: string]: string } (key = command, value = description of the command)

runConsoleCommandMem()

This method calls the POST endpoint /webapi/v3/consolecommands/execute/MEM.

  • Payload: None
  • Returns: SyshubMemCommandResult

runConsoleCommandP()

This method calls the POST endpoint /webapi/v3/consolecommands/execute/P.

  • Payload: None
  • Returns: SyshubPCommandLine[]

runWorkflow(string, bool, number|undefined)

This method calls the POST endpoint /webapi/v3/workflows/execute and starts an workflow execution optionally with job context.

  • Payload:
    • Param 1: string uuid sysHUB Workflow Uuid to execute
    • Param 2: bool async = true Determines whether to run the workflow synchronous or asynchronous.
    • Param 3: number|undefined jobId If set the workflow will be executed with the given job as currentjob.
  • Returns: [string, number]
    • Item 0 string: An Url sent by the sysHUB server refering to another Rest API Endpoint including the Uuid of the execution. This Uuid can be used in other Rest API calls to get the result of the execution.
    • Item 1 number: The HTTP Status code as this endpoint may return 201 or 202

runWorkflowAlias(string, any|undefined, string)

This method calls the endpoint /webapi/v3/workflows/execute/alias/... based on the given method (param 3) and returns whatever the workflow returns.

  • Payload:
    • Param 1: string alias sysHUB Workflow Alias name
    • Param 2: any|undefined payload Any payload you want to send to the workflows httpbody object
    • Param 3: 'DELETE'|'GET'|'POST'|'PUT' method Give one method to use for the communication with sysHUB, default is 'POST'
  • Returns: Whatever sysHUB has in its response dictionary object

Keywords

FAQs

Package last updated on 19 Jul 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc