-
Notifications
You must be signed in to change notification settings - Fork 2
Extending Functions
Wouter den Bakker edited this page Nov 2, 2021
·
3 revisions
The following classes and functions are available for extending the server, in addition to those from Validana Core
- This object should be extended when creating a custom api. See Extending Example.
- on("message", function): Add a function that should be called whenever there is an incoming api request. The arguments the function receives are the type of request, the data of the request and lastly an object containing information about the request and response.
- addMessageHandler(type: string, handler: Function, log?: boolean): Add a function that will be called when a new api request of given type is made. The arguments the function receives are the data of the api request and an object containing information about the request and response. Optionally log can be set to false to not log the incoming request, for example if the request contains sensitive data.
- cookieStringToMap(string): Turn a cookie string into a Map object.
Object containing information about an incoming api request and the response to be send.
- request: The incoming request:
- headers: object
- method: GET or POST
- url: Exact url of the request
- etc.
- latencyStart: When exactly was this message received. Used for latency metrics. Set to undefined to not record latency for this request.
- responseHeaders: Set to change the response headers.
- statusCode: Set the change the status code of the response.
- log: boolean: Set to false to not log outgoing message, for example if the request contains sensitive data.
- Protocol: Object for the protocol used for this request.
- canPush(): boolean: Does this protocol support push messages?
- sendPush(message, pushType, data): Send a push message. The first argument is this object, the second what type of push message this is and the third the data.
- version: string: To what version of the api was this send? Useful if there are only minor changes between versions and you want to reuse the same request handler.
- session: object: A simple object to store keys/values that remain till the websocket connection closes and carries over between requests.
- static get(name: string): Database: Get a database object with the given name (creating it if it does not yet exist).
- setup(options): Setup the database, must be done before it can be queried.
- isSetup(): boolean
- isActive(): boolean: Is that database setup and not yet shutdown.
- async shutdown(): Shutdown the database connection. Will happen automatically if the server shuts down.
- async query(query: string, params: Array): { rowCount: number, rows: Array }: Run a parameterized query against the database.
- async getConnection(): Get a single connection from the pool of database connections. Can be used if you want to execute multiple statements from the same connection, for example when using begin-commit. Must be release()d afterwards.
- async getDedicatedConnection(): Get a single connection, separate from the pool. Can be used for long lived connections without exhausting the connection pool.
- async notify(type: string, data): Send a message to all other server threats (subscribe with ServerEventEmitter.get("notification").subscribe()).
- on("setup", listener: Function): Provide a function that will be called once the database is setup.
- on("destroy", listener: Function): Provide a function that will be called when the database shutdowns.
- Config.get(): Get an object containing all config values.
- addStringConfig(name, defaultValue?, validator?): Add a config value for a string, optionally provide a default value or a validator that takes as input the provided value and should throw an error if it is invalid.
- addStringConfig(regexp, validator?): Add all config values/environment variables matching regexp.
- addNumberConfig(name, defaultValue?, validator?): Add a config value for a number
- addNumberConfig(regexp, validator?)
- addBoolConfig(name, defaultValue?, validator?): Add a config value for a boolean
- addBoolConfig(regexp, validator?)
- addObjectConfig(name, defaultValue?, validator?): Add a config for a json object.
- addObjectConfig(regexp, validator?)
A simple object for caching. Note that each worker uses its own cache, for more advanced caching solutions use something like Memcached or Redis. Can easily be turned off with VSERVER_CACHING config option.
- static add(key: string, update: function, duration?: number, override?: boolean): Add a new key to the cache (if override then override if exists). The function will be called to update the cache once its duration (in seconds) expired. Defaults to 5 minutes.
- static has(key): boolean
- static async get(key): Get a value from the cache. Will throw if it does not exist or if the function for updating the cache throws.
- static invalidate(key, newValue?): Immediately expire the cache. Optionally update the cache instead with a new value.
- static invalidateAll()
- static delete(key)
- static create(name, clearFrequency: number): Returns the cache object with the given name, creating it if it does not exist. Every clearfrequency (in seconds) it will remove any expired keys.
- add, has, get, invalidate, invalidateAll, delete: Same as static version.
- addAll(function, duration?, override?): Add a function (if override then override if exists) that will be used for any non-existent keys to automatically add them to the cache when requested. The function will receive the key name as the first argument.
- getMultiple(keys): Get multiple keys at once. To make this possible addAll should be called with a function that accepts a list of keys and returns them in the same order as requested.
- deleteExpired(): Delete all expired keys from the cache.
- deleteAll(): Remove all keys from the cache, as well as the function from addAll.
Can be used for the publish-subscriber pattern.
- static get(eventType: string): ServerEventEmitter: Get a event emitter for events of a given type.
- get("transactionId"): Will emit events for processed transactions of a given id.
- get("transactionAddress"): Will emit events for processed transactions send by/to a given address.
- get("transactionContract"): Will emit events for processed trnasactions for contracts with a given name.
- get("transaction"): Will emit events for any processed transaction.
- emit(data, subtype): Notify all subscribers with data. If subtype is provided only subscribers to that subtype will be notified.
- subscribe(message?, function, subtype?): Subscribe to an event emitter. If message is provided, it will automatically unsubscribe once the connection where the message came from closes. Upon emitting (for the given subtype) the provided function will be called.
- unsubscribe(message, subtype?): Unsubscribe from an event emitter.
- isSubscribed(message | Function, subtype?)
- hasSubscribers(subtype?): boolean
- getSubscribersSize(subtype?): number
- getSubtypesSize(): number: The number of subtypes with at least one subscriber.
- getSubtypes()
- Periodically generate an event. Takes care of errors and will skip generating an event if it is still busy with the previous one.
- constructor(function, frequency): Execute a function every frequency milliseconds.
- stop()
- static addTotalMetrics(names: string[], exporters: { format: Function }): Add gathering metrics with provided name. It will record a running total, which can be increased with Metrics.stats[name]++. An example would be the total api requests made to this server. The exporters should contain a function that takes as input an object, with for each name a number array, and should output a string/object.
- For example
addTotalMetrics(["requests"], { json: (metrics) => ({requests: Metrics.sum(metrics.requests)}));
- For example
- static addCurrentMetrics(names: string[], exporters: { format: Function }): Same as addTotalMetrics, but for metrics that go up and down. An example would be the current number of connections to the server.
- static sum(number[]): number: Helper function
- static avg(number[]): number: Helper function