ataraxia-service-contracts
v0.12.0
Published
Utils for defining contracts for use with ataraxia-services
Downloads
4
Readme
ataraxia-service-contracts
Light-weight service contracts for defining how services act. Used for RPC in Ataraxia.
This library is provided as a way to define contracts for services that may be used with Ataraxia, but do not necessarily register or consume them on their own. If you're interested in registering or consuming services ataraxia-services is what you want to depend on.
Usage
To get started install the ataraxia-service-contracts
library:
npm install ataraxia-service-contracts
Contracts can then be defined using the ServiceContract class:
import { ServiceContract } from 'ataraxia-service-contracts';
const EchoService = new ServiceContract()
.defineMethod('echo', {
returnType: stringType,
parameters: [
{
name: 'message',
type: stringType
}
]
})
.defineEvent('onEcho', {
parameters: [
{
name: 'message',
type: stringType
}
]
});
Or together with TypeScript:
import { ServiceContract, AsyncSubscribable } from 'ataraxia-service-contracts';
interface EchoService {
onEcho: AsyncSubscribable<this, [ message: string ]>;
echo(message: string): Promise<string>;
}
const EchoService = new ServiceContract<EchoService>()
.defineMethod('echo', {
returnType: stringType,
parameters: [
{
name: 'message',
type: stringType
}
]
})
.defineEvent('onEcho', {
parameters: [
{
name: 'message',
type: stringType
}
]
});
Using contracts in classes
When using classes the recommended way to mark what contract a class implements is to use the serviceContract decorator:
@serviceContract(EchoService)
class EchoServiceImpl {
async echo(message) {
return message;
}
}
If the decorator is not used you can define a static property called serviceContract instead:
class EchoServiceImpl {
static serviceContract = EchoService;
async echo(message) {
return message;
}
}
Contracts will traverse the prototype chain, so defining contract on extended classes work well:
@serviceContract(EchoService)
class AbstractEchoService {
async echo(message) {
return message;
}
}
class EchoServiceImpl extends AbstractEchoService {
}
Using contracts with objects
For plain objects the easiest way to use a contract is to use implement:
const instance = EchoService.implement({
async echo(message) {
return message;
}
});
As with classes a property may be used instead:
const instance = {
serviceContract: EchoService,
async echo(message) {
return message;
}
};