smartsocket/ts/smartsocket.classes.socketfunction.ts

87 lines
2.1 KiB
TypeScript
Raw Normal View History

2017-07-07 20:02:19 +00:00
import * as plugins from './smartsocket.plugins'
2016-08-07 13:37:52 +00:00
// import classes
2017-07-07 20:02:19 +00:00
import { Objectmap } from 'lik'
import { SocketRole } from './smartsocket.classes.socketrole'
2016-08-07 13:37:52 +00:00
2016-08-09 09:42:21 +00:00
// export interfaces
2016-08-09 16:22:30 +00:00
/**
* interface of the contructor options of class SocketFunction
*/
2016-08-12 01:22:36 +00:00
export interface ISocketFunctionConstructorOptions {
2017-07-07 20:02:19 +00:00
funcName: string
funcDef: any
allowedRoles: SocketRole[] // all roles that are allowed to execute a SocketFunction
}
2016-08-07 13:37:52 +00:00
2016-08-09 16:22:30 +00:00
/**
2016-08-12 01:22:36 +00:00
* interface of the Socket Function call, in other words the object that routes a call to a function
2016-08-09 16:22:30 +00:00
*/
export interface ISocketFunctionCall {
2017-07-07 20:02:19 +00:00
funcName: string
funcDataArg: any
}
2016-08-12 03:17:13 +00:00
/**
* interface for function definition of SocketFunction
*/
export interface IFuncDef {
2017-07-07 20:02:19 +00:00
(dataArg: any): PromiseLike<any>
2016-08-09 16:22:30 +00:00
}
2016-08-12 01:22:36 +00:00
// export objects
2017-07-07 20:02:19 +00:00
export let allSocketFunctions = new Objectmap<SocketFunction>()
2016-08-12 01:22:36 +00:00
2016-08-09 09:42:21 +00:00
// export classes
/**
2016-08-09 16:22:30 +00:00
* class that respresents a function that can be transparently called using a SocketConnection
2016-08-09 09:42:21 +00:00
*/
2016-08-07 13:37:52 +00:00
export class SocketFunction {
2017-07-07 20:02:19 +00:00
name: string
funcDef: IFuncDef
roles: SocketRole[]
2016-08-08 16:20:00 +00:00
2017-07-07 20:02:19 +00:00
/**
* the constructor for SocketFunction
*/
constructor (optionsArg: ISocketFunctionConstructorOptions) {
this.name = optionsArg.funcName
this.funcDef = optionsArg.funcDef
this.roles = optionsArg.allowedRoles
for (let socketRoleArg of this.roles) {
this._notifyRole(socketRoleArg)
}
allSocketFunctions.add(this) // map instance with Objectmap
}
2016-08-08 16:20:00 +00:00
2017-07-07 20:02:19 +00:00
/**
* invokes the function of this SocketFunction
*/
invoke (dataArg: ISocketFunctionCall): Promise<any> {
let done = plugins.smartq.defer()
if (dataArg.funcName === this.name) {
this.funcDef(dataArg.funcDataArg)
.then((resultData: any) => {
let funcResponseData: ISocketFunctionCall = {
funcName: this.name,
funcDataArg: resultData
}
done.resolve(funcResponseData)
})
} else {
throw new Error("SocketFunction.name does not match the data argument's .name!")
2016-08-08 16:20:00 +00:00
}
2017-07-07 20:02:19 +00:00
return done.promise
}
2016-08-08 16:20:00 +00:00
2017-07-07 20:02:19 +00:00
/**
* notifies a role about access to this SocketFunction
*/
private _notifyRole (socketRoleArg: SocketRole) {
socketRoleArg.addSocketFunction(this)
}
}