npm package: @mimik/api-helper
Description: helper for openAPI backend and mimik service
Author: mimik technology inc
Latest version: 3.0.4

## Modules

<dl>
<dt><a href="#module_api-helper">api-helper</a></dt>
<dd></dd>
</dl>

## Typedefs

<dl>
<dt><a href="#UUID">UUID</a> : <code>string</code></dt>
<dd><p>UUID string in RFC 4122 format.</p>
</dd>
<dt><a href="#PATH">PATH</a> : <code>string</code></dt>
<dd><p>File system path string.</p>
</dd>
</dl>

<a name="module_api-helper"></a>

## api-helper
**Example**  
```js
import apiHelper from '@mimik/api-helper';
// or
import { apiSetup, securityLib, getAPIFile, validateSecuritySchemes, extractProperties, setupServerFiles } from '@mimik/api-helper';
```

* [api-helper](#module_api-helper)
    * _async_
        * [~apiSetup(setup, registeredOperations, securityHandlers, extraFormats, config, correlationId)](#module_api-helper..apiSetup) ⇒ <code>Promise.&lt;object&gt;</code>
        * [~getAPIFile(apiFilename, correlationId, options)](#module_api-helper..getAPIFile) ⇒ <code>Promise.&lt;object&gt;</code>
        * [~setupServerFiles(apiFilename, controllersDirectory, buildDirectory, correlationId, options)](#module_api-helper..setupServerFiles) ⇒ <code>Promise.&lt;object&gt;</code>
    * _sync_
        * [~securityLib(config)](#module_api-helper..securityLib) ⇒ <code>object</code>
        * [~validateSecuritySchemes(apiDefinition, correlationId)](#module_api-helper..validateSecuritySchemes) ⇒ <code>Array.&lt;string&gt;</code>
        * [~extractProperties(apiDefinition, controllersDirectory, buildDirectory, correlationId)](#module_api-helper..extractProperties) ⇒ <code>void</code>

<a name="module_api-helper..apiSetup"></a>

### api-helper~apiSetup(setup, registeredOperations, securityHandlers, extraFormats, config, correlationId) ⇒ <code>Promise.&lt;object&gt;</code>
Set up the API to be used for a service

**Kind**: inner method of [<code>api-helper</code>](#module_api-helper)  
**Returns**: <code>Promise.&lt;object&gt;</code> - The initialized OpenAPIBackend instance.  
**Category**: async  
**Throws**:

- <code>Error</code> Rejects with an error if the initialization failed.

The following scheme names are reserved: `SystemSecurity`, `AdminSecurity`, `UserSecurity`, `PeerSecurity`, `ApiKeySecurity`.
The following security schemes can be defaulted: `SystemSecurity`, `AdminSecurity`, `UserSecurity`, `ApiKeySecurity`.
The secOptions in the options property passed when using `init` allows the following operations:
- introduce a custom security scheme, in this case secOptions contains: { newSecurityScheme: {function}newSecurityHandler },
- disable a security scheme that is defined in the swagger API, in this case secOptions contains: { securitySchemeToDisable: { {boolean}notEnabled: true } },
- overwrite an existing security scheme, in this case secOptions contains: { securitySchemeToOverwrite: {function}newSecurityHandler }.
If the secOptions is not present either to introduce, disable or overwrite a security scheme that is present in the swagger API file an error is generated.
If the secOptions contains unused security schemes, an error is generated.

The default formats for validation are: `date`, `time`, `date-time`, `byte`, `uuid`, `uri`, `email`, `ipv4`, `ipv6`, `semver`, `ip`.

**Requires**: <code>module:@mimik/response-helper</code>, <code>module:@mimik/sumologic-winston-logger</code>, <code>module:openapi-backend</code>  

| Param | Type | Description |
| --- | --- | --- |
| setup | <code>object</code> | Object containing the apiFilename and the existing security schemes in the API definition. |
| setup.apiFilename | [<code>PATH</code>](#PATH) | Path to the resolved API definition file. |
| setup.existingSecuritySchemes | <code>Array.&lt;string&gt;</code> | Known security scheme names present in the API definition. |
| setup.definedSecuritySchemes | <code>Array.&lt;string&gt;</code> | All security scheme names defined in the API definition. |
| registeredOperations | <code>object</code> | Map of operationId to handler function to register for the API. |
| securityHandlers | <code>object</code> | Map of security scheme name to handler object to add for the service. |
| extraFormats | <code>object</code> | Map of format name to format definition for validating properties. Each entry is either an empty object (to use a built-in ajv-formats format) or an object with `type` and `validate` properties (to define a custom format). |
| config | <code>object</code> | Configuration of the service. |
| correlationId | [<code>UUID</code>](#UUID) | CorrelationId when logging activities. |

<a name="module_api-helper..getAPIFile"></a>

### api-helper~getAPIFile(apiFilename, correlationId, options) ⇒ <code>Promise.&lt;object&gt;</code>
Gets and resolves the API definition, loading from local file, Bitbucket, or SwaggerHub, and stores it in the given PATH location.

**Kind**: inner method of [<code>api-helper</code>](#module_api-helper)  
**Returns**: <code>Promise.&lt;object&gt;</code> - The API file itself.  
**Category**: async  
**Throws**:

- <code>Error</code> Rejects with an error if the apiFilename resolution generates an error or the request to the API provider fails or the file cannot be saved.

`apiInfo` options has the following format:
``` javascript
{
   "provider": "provider of the api file, can be `swaggerhub` or `bitbucket`",
   "apiBasicAuth": {
     "username": "username for bitbucket",
     "password": "password for bitbucket"
   },
   "apiApiKey": "apiKey to access private API on swaggerhub, can be optional if the API is accessible publicly"
}
```

**Requires**: <code>module:@mimik/request-retry</code>, <code>module:@mimik/response-helper</code>, <code>module:@mimik/sumologic-winston-logger</code>, <code>module:fs</code>, <code>module:js-yaml</code>, <code>module:path</code>  

| Param | Type | Description |
| --- | --- | --- |
| apiFilename | [<code>PATH</code>](#PATH) | Name of the file where the API file will be stored. |
| correlationId | [<code>UUID</code>](#UUID) | CorrelationId when logging activities. |
| options | <code>object</code> | Options associated with the call. Use to pass `metrics` to `rpRetry` and `apiInfo` to access the api file in the api provider. |

<a name="module_api-helper..setupServerFiles"></a>

### api-helper~setupServerFiles(apiFilename, controllersDirectory, buildDirectory, correlationId, options) ⇒ <code>Promise.&lt;object&gt;</code>
Sets up and validates files for the server

**Kind**: inner method of [<code>api-helper</code>](#module_api-helper)  
**Returns**: <code>Promise.&lt;object&gt;</code> - The API file, the API filename, the existing known security schemes and the defined security schemes.  
**Category**: async  
**Throws**:

- <code>Error</code> Rejects with an error for many reasons associated with getAPIFile or validateSecuritySchemes or extractProperties.

**Requires**: <code>module:@mimik/request-retry</code>, <code>module:@mimik/response-helper</code>, <code>module:@mimik/sumologic-winston-logger</code>, <code>module:fs</code>, <code>module:js-yaml</code>, <code>module:path</code>  

| Param | Type | Description |
| --- | --- | --- |
| apiFilename | [<code>PATH</code>](#PATH) | Name of the file where the API file will be stored. |
| controllersDirectory | [<code>PATH</code>](#PATH) | Directory to find the controller files. |
| buildDirectory | [<code>PATH</code>](#PATH) | Directory where the register file will be stored. |
| correlationId | [<code>UUID</code>](#UUID) | CorrelationId when logging activities. |
| options | <code>object</code> | Options associated with the call. Use to pass `metrics` to `rpRetry` and `apiKey` to access private API. |

<a name="module_api-helper..securityLib"></a>

### api-helper~securityLib(config) ⇒ <code>object</code>
Implements the security flows for the API.

**Kind**: inner method of [<code>api-helper</code>](#module_api-helper)  
**Returns**: <code>object</code> - An object containing `SystemSecurity`, `AdminSecurity`, `UserSecurity`, and `ApiKeySecurity` handlers.

This function is used to set up the following security handlers for the API:
- `SystemSecurity` - used for system-to-system operations, validates client credentials tokens.
- `AdminSecurity` - used for admin operations, validates admin/subAdmin client credentials tokens.
- `UserSecurity` - used for user operations, validates implicit flow tokens.
- `ApiKeySecurity` - used for API key authenticated operations, validates API keys from headers.
The security handlers are used to validate the tokens and scopes for the API operations.  
**Category**: sync  
**Requires**: <code>module:@mimik/swagger-helper</code>, <code>module:jsonwebtoken</code>  

| Param | Type | Description |
| --- | --- | --- |
| config | <code>object</code> | Configuration of the service. |

<a name="module_api-helper..validateSecuritySchemes"></a>

### api-helper~validateSecuritySchemes(apiDefinition, correlationId) ⇒ <code>Array.&lt;string&gt;</code>
Validates the known SecuritySchemes: `SystemSecurity`, `AdminSecurity`, `UserSecurity`, `PeerSecurity`, `ApiKeySecurity`.

**Kind**: inner method of [<code>api-helper</code>](#module_api-helper)  
**Returns**: <code>Array.&lt;string&gt;</code> - An array of the known securitySchemes that are in the API definition.  
**Category**: sync  
**Throws**:

- <code>Error</code> An error is thrown if a validation fails.

**Requires**: <code>module:@mimik/sumologic-winston-logger</code>, <code>module:@mimik/response-helper</code>  

| Param | Type | Description |
| --- | --- | --- |
| apiDefinition | <code>object</code> | JSON object containing the API definition. |
| correlationId | [<code>UUID</code>](#UUID) | CorrelationId when logging activities. |

<a name="module_api-helper..extractProperties"></a>

### api-helper~extractProperties(apiDefinition, controllersDirectory, buildDirectory, correlationId) ⇒ <code>void</code>
Extracts the properties from API definition and creates a `register.js` file in the build directory binding the handler with the controller operations.

**Kind**: inner method of [<code>api-helper</code>](#module_api-helper)  
**Category**: sync  
**Throws**:

- <code>Error</code> An error is thrown for many reasons, like operationId does not exist in controllers, controller does not exist...

**Requires**: <code>module:@mimik/response-helper</code>, <code>module:@mimik/sumologic-winston-logger</code>, <code>module:fs</code>  

| Param | Type | Description |
| --- | --- | --- |
| apiDefinition | <code>object</code> | JSON object containing the API definition. |
| controllersDirectory | [<code>PATH</code>](#PATH) | Directory to find the controller files. |
| buildDirectory | [<code>PATH</code>](#PATH) | Directory where the register file will be stored. |
| correlationId | [<code>UUID</code>](#UUID) | CorrelationId when logging activities. |

<a name="UUID"></a>

## UUID : <code>string</code>
UUID string in RFC 4122 format.

**Kind**: global typedef  
<a name="PATH"></a>

## PATH : <code>string</code>
File system path string.

**Kind**: global typedef