@wbc-nodejs/core
v3.0.5
Published
Core Nodejs library for Webcoupers
Maintainers
Readme
Reusable Nodejs Library
This is a repository for Reusable Nodejs library, covering authentication, response model, Error handling, validation e.t.c
Installation
Run npm i @wbc-nodejs/core to install with npm or yarn add @wbc-nodejs/core to install with yarn
Required Environment Variables
- APP_KEY
- APP_ENV
Configurations
corsOptions(config) ⇒ CorsOptions
Kind: global function
Returns: CorsOptions - Cors Option
| Param | Type | Description | | --- | --- | --- | | config | Object | the cors configuration | | [config.whitelist] | Array.<string> | Array of url to whitelist | | [config.whitelistRegEx] | Array.<RegExp> | Array of url to whitelist using matching | | config.appURL | string | The application url | | [config.exposedHeaders] | Array | The application url |
CorsOptions : Object
Kind: global typedef
Properties
| Name | Type | Description | | --- | --- | --- | | credentials | boolean | The cors credentials. | | exposedHeaders | Array.<string> | The headers to expose | | origin | function | The origin function |
jwtConfig
Kind: global constant
Properties
| Name | Type | | --- | --- | | ACTIVATION_TOKEN_LIFESPAN | string | | SECRET_KEY | string | | ACCESS_TOKEN_LIFESPAN | string | | REFRESH_TOKEN_LIFESPAN | string |
regExp
Kind: global constant
Properties
| Name | Type | | --- | --- | | NUMBER | RegExp | | POSITIVE_NUMBER | RegExp | | POSITIVE_NUMBER_DECIMAL_POINT | RegExp | | EMAIL | RegExp | | PHONE_NUMBER | RegExp | | ALPHA_NUMERIC | RegExp | | ALPHA_NUMERIC_COMMA_DOT | RegExp | | ALPHA_NUMERIC_PLANE | RegExp | | PASSWORD | RegExp | | URL | RegExp | | UUID | RegExp |
Error Classes
Classes
CustomError
Kind: global class
new CustomError(message, [config])
| Param | Type | | --- | --- | | message | string | | [config] | Object | | [config.httpStatusCode] | number | | [config.stackTrace] | string | | [config.subCode] | number | | [config.reason] | * |
RequestValidationError
Kind: global class
new RequestValidationError(message, [config])
| Param | Type | | --- | --- | | message | string | | [config] | Object | | [config.subCode] | number | | [config.reason] | * |
AuthenticationError
Kind: global class
new AuthenticationError(message, [config])
| Param | Type | | --- | --- | | message | string | | [config] | Object | | [config.subCode] | number | | [config.reason] | * |
AuthorizationError
Kind: global class
new AuthorizationError(message, [config])
| Param | Type | | --- | --- | | message | string | | [config] | Object | | [config.subCode] | number | | [config.reason] | * |
NotFoundError
Kind: global class
new NotFoundError(message, [config])
| Param | Type | | --- | --- | | message | string | | [config] | Object | | [config.subCode] | number | | [config.reason] | * |
ConflictError
Kind: global class
new ConflictError(message, [config])
| Param | Type | | --- | --- | | message | string | | [config] | Object | | [config.subCode] | number | | [config.reason] | * |
Utility Functions
Constants
Functions
Typedefs
env : Object.<string, *>
Kind: global constant
isTypeOf(varToCheck, type) ⇒ * | boolean
Kind: global function
Returns: * | boolean - check - the strict type of a variable
| Param | Type | Description | | --- | --- | --- | | varToCheck | * | variable to check its type | | type | string | The type to check against |
getDistinctFrequency(array) ⇒ Object
Kind: global function
Returns: Object - Frequency counter
| Param | Type | Description | | --- | --- | --- | | array | Array | string | The port to normalize |
getEnv() ⇒ Object.<string, *>
get all the system environment variables
Kind: global function
Returns: Object.<string, *> - Environment variables
setEnv(newEnv) ⇒ null
set a new environment variable or update existing one
Kind: global function
Returns: null - Null
| Param | Type | Description | | --- | --- | --- | | newEnv | Object | The new environment variable(s) as object |
paginate(model) ⇒ PaginationFunction
Paginates model
Kind: global function
Returns: PaginationFunction - Function to paginate the specified model
| Param | Type | Description | | --- | --- | --- | | model | Object | model to add pagination to | | [model.findAndCountAll] | function | inbuilt model function |
removeFileExtension(fileName) ⇒ string | *
To remove extension from a file
Kind: global function
Returns: string | * - Name without extension
| Param | Type | Description | | --- | --- | --- | | fileName | string | The name of the file to remove its extension |
isValidBase64Image(base64) ⇒ string | *
Check if a string is a valid base64
Kind: global function
Returns: string | * - If the string is base64 formatted
| Param | Type | Description | | --- | --- | --- | | base64 | string | the base 64 string |
pickFromObject(obj, acceptedKeys) ⇒ Object | *
To create a new object containing a specified key from an existing object
Kind: global function
Returns: Object | * - Newly created object
| Param | Type | Description | | --- | --- | --- | | obj | Object | object to pick key value pair from | | acceptedKeys | Array.<string> | the keys to pick from the object |
discardFromObject(obj, forbiddenKeys) ⇒ Object | *
To create a new object that does not contain a specified key from an existing object
Kind: global function
Returns: Object | * - Newly created object
| Param | Type | Description | | --- | --- | --- | | obj | Object | Object to create from | | forbiddenKeys | Array.<string> | the keys that should not exist in the new object |
getBaseDomainFromUrl(url) ⇒ string
To get base domain from a giving url
Kind: global function
Returns: string - The base domain
| Param | Type | Description | | --- | --- | --- | | url | string | The url to extract base domain from |
getCookieDomain(req) ⇒ string
To get cookie domain
Kind: global function
Returns: string - The base domain
| Param | Type | Description | | --- | --- | --- | | req | Object | Express request object |
getTokensFromRequest(req, [config]) ⇒ Object
To get tokens from request
Kind: global function
Returns: Object - Token Object
| Param | Type | Description | | --- | --- | --- | | req | Object | Express request object | | [config] | Object | key to find accessToken | | [config.accessTokenKey] | string | key to find accessToken | | [config.refreshTokenKey] | string | key to find accessToken |
setTokensToResponse(res, tokens, [config]) ⇒ string
To set token to response
Kind: global function
Returns: string - Referer Url
| Param | Type | Description | | --- | --- | --- | | res | Object | Express response object | | tokens | Object | The tokens to set | | [tokens.access] | string | The access token to set | | [tokens.refresh] | string | The access token to set | | [config] | Object | Other configurations | | [config.cookieDomain] | string | The domain to set the token cookies on | | [config.accessTokenKey] | string | The key to use for accessToken | | [config.refreshTokenKey] | string | The key to use for refreshToken | | [config.cookieLifeInDays] | number | The number of days before cookie expires |
normalizePort(port) ⇒ boolean | number | *
Kind: global function
Returns: boolean | number | * - Normalized port
| Param | Type | Description | | --- | --- | --- | | port | string | number | The port to normalize |
updateQueryParams(route, params, [customIdentifier]) ⇒ string
Kind: global function
Returns: string - The updated url with the query params attached
| Param | Type | | --- | --- | | route | string | | params | Object | | [customIdentifier] | string |
base64Encode(val, [urlEncode]) ⇒ string
Kind: global function
Returns: string - The encoded string
| Param | Type | | --- | --- | | val | * | | [urlEncode] | boolean |
base64Decode(val, [urlEncoded]) ⇒ string
Kind: global function
Returns: string - The decoded string
| Param | Type | | --- | --- | | val | * | | [urlEncoded] | boolean |
convertToSlug(text) ⇒ string | *
Kind: global function
Returns: string | * - slug
| Param | Type | | --- | --- | | text | string |
PaginationFunction ⇒ Object
Kind: global typedef
Returns: Object - Paginated data
| Param | Type | Default | Description | | --- | --- | --- | --- | | [page] | string | number | 1 | page to query | | [limit] | string | number | 10 | limit for the query | | [options] | Object | | Options for the model |
JWT Helper
Modules
Typedefs
jwt
- jwt
- ~makeToken(user, [lifeSpan]) ⇒ undefined | string
- ~verifyToken(token, [includeSignature]) ⇒ Object
- ~generateTokens(user) ⇒ Object
- ~renewAccessToken(refreshToken, getUser) ⇒ Promise.<Array>
jwt~makeToken(user, [lifeSpan]) ⇒ undefined | string
To generate a jwt
Kind: inner method of jwt
Returns: undefined | string - The generated token string
| Param | Type | Description | | --- | --- | --- | | user | Object | The user to create a token for | | [lifeSpan] | string | The lifespan of the token to be created |
jwt~verifyToken(token, [includeSignature]) ⇒ Object
To verify a given jwt
Kind: inner method of jwt
Returns: Object - the user object
| Param | Type | Default | Description | | --- | --- | --- | --- | | token | String | | the access token string | | [includeSignature] | Boolean | true | Whether or not to include signature |
jwt~generateTokens(user) ⇒ Object
To generate both access and refresh token for a given user
Kind: inner method of jwt
Returns: Object - The generated token object containing access token and refresh token
| Param | Type | Description | | --- | --- | --- | | user | Object | The user to generate tokens for |
jwt~renewAccessToken(refreshToken, getUser) ⇒ Promise.<Array>
To get new access token from a refresh token
Kind: inner method of jwt
Returns: Promise.<Array> - The new access token and the user data
| Param | Type | Description | | --- | --- | --- | | refreshToken | string | the refresh token | | getUser | RefreshTokenGetUser | function | Function to get user |
RefreshTokenGetUser ⇒ Object
To get user data to be used to regenerate token
Kind: global typedef
Returns: Object - the user
| Param | Type | | --- | --- | | id | string |
App Logger
logger
Application logger
Kind: global constant
Properties
| Name | Type | | --- | --- | | stream | * | | add | function | | info | function |
Response Helper
response
response~render(req, res, template, [data], [statusCode]) ⇒ HTMLDocument
Kind: inner method of response
Returns: HTMLDocument - Full html content
| Param | Type | Default | Description | | --- | --- | --- | --- | | req | Object | | Express request object | | res | Object | | Express response object | | template | String | | Http status code for the response | | [data] | Object | | Data to be return as part of response body | | [statusCode] | Number | 200 | Http status code for the response |
response~success(res, statusCode, [data], [message]) ⇒ JSON
Kind: inner method of response
Returns: JSON - Formatted JSON server response
| Param | Type | Description | | --- | --- | --- | | res | object | Express response object | | statusCode | Number | Http status code for the response | | [data] | object | Data to be return as part of response body | | [message] | String | Message accompanying the response data |
response~ok(res, [data], [message]) ⇒ JSON
Kind: inner method of response
Returns: JSON - Formatted JSON server response
| Param | Type | Description | | --- | --- | --- | | res | object | Express response object | | [data] | object | Data to be return as part of response body | | [message] | String | Message accompanying the response data |
response~created(res, data, [message]) ⇒ JSON
Kind: inner method of response
Returns: JSON - Formatted JSON server response
| Param | Type | Description | | --- | --- | --- | | res | object | Express response object | | data | object | Data to be return as part of response body | | [message] | String | Message accompanying the response data |
response~redirect(res, url, [code]) ⇒ Null
Kind: inner method of response
Returns: Null - Null
| Param | Type | Description | | --- | --- | --- | | res | object | Express response object | | url | String | url to redirect to | | [code] | Number | 301 or 302 based on permanent or temporary |
Validators
Objects
Typedefs
validator : object
Kind: global namespace
validator.body : ValidatorInstance
Kind: static constant of validator
validator.param : ValidatorInstance
Kind: static constant of validator
validator.query : ValidatorInstance
Kind: static constant of validator
CustomValidator ⇒ *
Kind: global typedef
Returns: * - Validation chain
| Param | Type | Description | | --- | --- | --- | | [fieldName] | string | The field to validate | | [message] | string | Error message |
CustomConfirmValidator ⇒ *
Kind: global typedef
Returns: * - Validation chain
| Param | Type | Description | | --- | --- | --- | | [fieldName] | string | The field to validate | | [benchmark] | string | What to benchmark against | | [message] | string | Error message |
CustomMatchPatterValidator ⇒ *
Kind: global typedef
Returns: * - Validation chain
| Param | Type | Description | | --- | --- | --- | | fieldName | string | The field to validate | | pattern | RegExp | pattern to test for | | [message] | string | Error message |
CustomRequiredValidator ⇒ Array
Kind: global typedef
Returns: Array - Validation chain
| Param | Type | Description | | --- | --- | --- | | ...fieldNames | string | Name of the required field(s) |
ValidatorInstance : Object
Kind: global typedef
Properties
| Name | Type | | --- | --- | | email | CustomValidator | | password | CustomValidator | | confirm | CustomConfirmValidator | | matchPattern | CustomMatchPatterValidator | | required | CustomRequiredValidator |
Middlewares
decodeCurrentUser([accessTokenKey], [refreshTokenKey]) ⇒ function
Kind: global function
Returns: function - Express middleware function
| Param | Type | Default | Description | | --- | --- | --- | --- | | [accessTokenKey] | string | "accessToken" | The accessToken key | | [refreshTokenKey] | string | "refreshToken" | The accessToken key |
errorHandler([includeStackTrace]) ⇒ function
Kind: global function
Returns: function - Express middleware function
| Param | Type | Description | | --- | --- | --- | | [includeStackTrace] | boolean | Whether or not to include stack trace |
requireAuthentication([message]) ⇒ function
Kind: global function
Returns: function - Express middleware function
| Param | Type | Description | | --- | --- | --- | | [message] | string | The message to display to user |
preloadSwagger(documentation) ⇒ function
Kind: global function
Returns: function - Middleware to update documentation properties
| Param | Type | Description | | --- | --- | --- | | documentation | Object | Swagger json documentation |
refreshAccessToken([config]) ⇒ function
Kind: global function
Returns: function - Middleware to refresh accessToken
| Param | Type | Description | | --- | --- | --- | | [config] | Object | Configuration object | | [config.accessTokenKey] | string | key to find accessToken | | [config.refreshTokenKey] | string | key to find refreshToken | | [config.forceRefreshEvenIfNotExpire] | boolean | Whether or not to refresh even if the token has not yet expired | | config.getUser | RefreshTokenGetUser | Function to get user data |
requirePrivilege(requirements, [config]) ⇒ function
Kind: global function Returns: function - Privilege checker middleware
| Param | Type | Default | Description | | --- | --- | --- | --- | | requirements | Object | | The requirements | | [requirements.has] | string | function | | Checks for this privilege | | [requirements.hasAll] | Array.<string> | function | | Checks for all privilege in this array | | [requirements.hasAny] | Array.<string> | function | | Checks for any privilege in this array | | [config] | Object | | other configurations | | [config.errorMessage] | string | | Error message to show user in case requirement not met | | [config.privilegeKey] | string | "privilegeList" | Key to check privilege list in req.user |
validationResult([message]) ⇒ function
Kind: global function
Returns: function - Middleware to update documentation properties
| Param | Type | Description | | --- | --- | --- | | [message] | string | General error message to return |
