# Services

CoBox server makes use of 'service' functions which are made available in the controllers in order to perform simple to complex functionality. This enables us to write small and self-contained functions which can be used in multiple locations in the application.

To add a new service, define the function in the following manner:

```javascript
// app/serivces/my-service.js

module.exports = setupMyService

function setupMyService (api) {
  /**
   * don't forget to document your service using jsdoc
   * @param {Object} params - detail the expected parameters here
   * @returns {string|Buffer|Object|undefined}
   */
  return function myService (params) {
    // implement your functionality here
  }
}
```

The API here is an instance of a `Map` object (see [inject.js](../inject.js)).

In order to make your service available in the controllers, you must add it to the API. Typically this is done in [inject.js](../inject.js).

```javascript
// simply add your new service below the other already existing services
api.set('services.my-service', setupMyService(api))
```

However some functionality cannot be initialized until after authentication (such as the creation of a Corestore due to the encryption of the `parent_key`).
In this case, it must be added in the [unlock](./unlock.js) service, and removed in the [lock](./lock.js) service, to ensure it is properly protected.

Finally, you must load the service in the relevant controller. This can either be done by caching the service in the controller's `ready` function, or by accessing the service at run time in the relevant controller action via `const myService = this._api.get('services.my-service')`.

Setting up the API in this way enables testing the controller functionality in a granular manner by stubbing out service functions. This keeps the test suite tidy, and highly granular. See the [test suite](../../test) for examples.
