Services

By default service classes are located in APP_ROOT/services/**/* where APP_ROOT is the application base folder. The location can be changed using the servicesRoot configuration property. All service classes must be decorated with the @service decorator. The @service requires a string argument which defines the key to use when injecting the service using the @inject(...KEYS) decorator. By default each request gets its own instance of the injected service.

import { service } from 'kikwit';
@service('adder')
export class Adder {
    add(a, b) {
        return a + b;
    }
}
import { controller } from 'kikwit';
@inject('adder')
@controller
export class Arithm {   
    sum(context) {     
        let [a, b] = [7, 11];
        let sum = context.services.adder.add(a, b); // context.services.adder from @inject('adder')  
        return context.sendJSON({ a, b, sum });
    }
}

It is possible to get a service injected as a singleton by prefixing the key passed to the @inject(...KEYS) decorator with @.

import { service } from 'kikwit';
@service('adder')
export class Adder {   
    add(a, b) {
        return a + b;
    }
}
import { controller } from 'kikwit';
@inject('@adder') // '@adder' instead of 'adder'
@controller
export class Arithm {    
    sum(context) {        
        let [a, b] = [7, 11];
        let sum = context.services.adder.add(a, b); // context.services.adder from @inject('@adder')      
        return context.sendJSON({ a, b, sum });
    }
}

It is also possible to get the same instance of a service injected into an action across multiple requests by prefixing the key passed to the @inject(...KEYS) decorator with @@.

import { service } from 'kikwit';
@service('adder')
export class Adder {  
    add(a, b) {
        return a + b;
    }
}
import { controller } from 'kikwit';
@controller
export class Arithm {   
    @inject('@@adder') // '@@adder' instead of 'adder'
    sum(context) {      
        let [a, b] = [7, 11];
        let sum = context.services.adder.add(a, b); // context.services.adder from @inject('@@adder')  
        return context.sendJSON({ a, b, sum });
    }
}

In the example above, the instance injected into the sum action will only be reused by request to the sum action only.

To restrict a service to always be injected as a singleton, please pass true as a second argument to @service([KEY], [SINGLETON]) decorator.

import { service } from 'kikwit';
@service('adder', true)
export class Adder {  
    add(a, b) {
        return a + b;
    }
}

In the example above Adder will always get injected as a singleton regardless of how the format of the key used at the injection point.

Services injected at controller level are available to all of controller's actions.

results matching ""

    No results matching ""