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
corsOptions(config) ⇒ 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 |
Object
CorsOptions : 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 |
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
- RequestValidationError
- AuthenticationError
- AuthorizationError
- NotFoundError
- ConflictError
CustomError
new CustomError(message, [config])
Param | Type |
---|---|
message | string |
[config] | Object |
[config.httpStatusCode] | number |
[config.stackTrace] | string |
[config.subCode] | number |
[config.reason] | * |
RequestValidationError
new RequestValidationError(message, [config])
Param | Type |
---|---|
message | string |
[config] | Object |
[config.subCode] | number |
[config.reason] | * |
AuthenticationError
new AuthenticationError(message, [config])
Param | Type |
---|---|
message | string |
[config] | Object |
[config.subCode] | number |
[config.reason] | * |
AuthorizationError
new AuthorizationError(message, [config])
Param | Type |
---|---|
message | string |
[config] | Object |
[config.subCode] | number |
[config.reason] | * |
NotFoundError
new NotFoundError(message, [config])
Param | Type |
---|---|
message | string |
[config] | Object |
[config.subCode] | number |
[config.reason] | * |
ConflictError
new ConflictError(message, [config])
Param | Type |
---|---|
message | string |
[config] | Object |
[config.subCode] | number |
[config.reason] | * |
Utility Functions
Constants
-
env :
Object.<string, *>
Functions
-
isTypeOf(varToCheck, type) ⇒
*
|boolean
-
getDistinctFrequency(array) ⇒
Object
-
getEnv() ⇒
Object.<string, *>
-
get all the system environment variables
-
setEnv(newEnv) ⇒
null
-
set a new environment variable or update existing one
-
paginate(model) ⇒
PaginationFunction
-
Paginates model
-
removeFileExtension(fileName) ⇒
string
|*
-
To remove extension from a file
-
isValidBase64Image(base64) ⇒
string
|*
-
Check if a string is a valid base64
-
pickFromObject(obj, acceptedKeys) ⇒
Object
|*
-
To create a new object containing a specified key from an existing object
-
discardFromObject(obj, forbiddenKeys) ⇒
Object
|*
-
To create a new object that does not contain a specified key from an existing object
-
getBaseDomainFromUrl(url) ⇒
string
-
To get base domain from a giving url
-
getCookieDomain(req) ⇒
string
-
To get cookie domain
-
getTokensFromRequest(req, [config]) ⇒
Object
-
To get tokens from request
-
setTokensToResponse(res, tokens, [config]) ⇒
string
-
To set token to response
-
normalizePort(port) ⇒
boolean
|number
|*
-
updateQueryParams(route, params, [customIdentifier]) ⇒
string
-
base64Encode(val, [urlEncode]) ⇒
string
-
base64Decode(val, [urlEncoded]) ⇒
string
-
convertToSlug(text) ⇒
string
|*
Typedefs
-
PaginationFunction ⇒
Object
Object.<string, *>
env :
*
| boolean
isTypeOf(varToCheck, type) ⇒ 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 |
Object
getDistinctFrequency(array) ⇒ Kind: global function
Returns: Object
- Frequency counter
Param | Type | Description |
---|---|---|
array |
Array | string
|
The port to normalize |
Object.<string, *>
getEnv() ⇒ get all the system environment variables
Kind: global function
Returns: Object.<string, *>
- Environment variables
null
setEnv(newEnv) ⇒ 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 |
PaginationFunction
paginate(model) ⇒ 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 |
string
| *
removeFileExtension(fileName) ⇒ 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 |
string
| *
isValidBase64Image(base64) ⇒ 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 |
Object
| *
pickFromObject(obj, acceptedKeys) ⇒ 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 |
Object
| *
discardFromObject(obj, forbiddenKeys) ⇒ 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 |
string
getBaseDomainFromUrl(url) ⇒ 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 |
string
getCookieDomain(req) ⇒ To get cookie domain
Kind: global function
Returns: string
- The base domain
Param | Type | Description |
---|---|---|
req | Object |
Express request object |
Object
getTokensFromRequest(req, [config]) ⇒ 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 |
string
setTokensToResponse(res, tokens, [config]) ⇒ 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 |
boolean
| number
| *
normalizePort(port) ⇒ Kind: global function
Returns: boolean
| number
| *
- Normalized port
Param | Type | Description |
---|---|---|
port |
string | number
|
The port to normalize |
string
updateQueryParams(route, params, [customIdentifier]) ⇒ Kind: global function
Returns: string
- The updated url with the query params attached
Param | Type |
---|---|
route | string |
params | Object |
[customIdentifier] | string |
string
base64Encode(val, [urlEncode]) ⇒ Kind: global function
Returns: string
- The encoded string
Param | Type |
---|---|
val | * |
[urlEncode] | boolean |
string
base64Decode(val, [urlEncoded]) ⇒ Kind: global function
Returns: string
- The decoded string
Param | Type |
---|---|
val | * |
[urlEncoded] | boolean |
string
| *
convertToSlug(text) ⇒ Kind: global function
Returns: string
| *
- slug
Param | Type |
---|---|
text | string |
Object
PaginationFunction ⇒ 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
-
RefreshTokenGetUser ⇒
Object
-
To get user data to be used to regenerate token
jwt
-
jwt
-
~makeToken(user, [lifeSpan]) ⇒
undefined
|string
-
~verifyToken(token, [includeSignature]) ⇒
Object
-
~generateTokens(user) ⇒
Object
-
~renewAccessToken(refreshToken, getUser) ⇒
Promise.<Array>
-
~makeToken(user, [lifeSpan]) ⇒
undefined
| string
jwt~makeToken(user, [lifeSpan]) ⇒ 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 |
Object
jwt~verifyToken(token, [includeSignature]) ⇒ 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 |
Object
jwt~generateTokens(user) ⇒ 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 |
Promise.<Array>
jwt~renewAccessToken(refreshToken, getUser) ⇒ 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 |
Object
RefreshTokenGetUser ⇒ 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
-
~success(res, statusCode, [data], [message]) ⇒
JSON
-
~ok(res, [data], [message]) ⇒
JSON
-
~created(res, data, [message]) ⇒
JSON
-
~redirect(res, url, [code]) ⇒
Null
-
~render(req, res, template, [data], [statusCode]) ⇒
HTMLDocument
response~render(req, res, template, [data], [statusCode]) ⇒ 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 |
JSON
response~success(res, statusCode, [data], [message]) ⇒ 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 |
JSON
response~ok(res, [data], [message]) ⇒ 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 |
JSON
response~created(res, data, [message]) ⇒ 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 |
Null
response~redirect(res, url, [code]) ⇒ 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
-
validator :
object
Typedefs
-
CustomValidator ⇒
*
-
CustomConfirmValidator ⇒
*
-
CustomMatchPatterValidator ⇒
*
-
CustomRequiredValidator ⇒
Array
-
ValidatorInstance :
Object
object
validator : Kind: global namespace
-
validator :
object
ValidatorInstance
validator.body : Kind: static constant of validator
ValidatorInstance
validator.param : Kind: static constant of validator
ValidatorInstance
validator.query : 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 |
Array
CustomRequiredValidator ⇒ Kind: global typedef
Returns: Array
- Validation chain
Param | Type | Description |
---|---|---|
...fieldNames | string |
Name of the required field(s) |
Object
ValidatorInstance : Kind: global typedef
Properties
Name | Type |
---|---|
CustomValidator |
|
password | CustomValidator |
confirm | CustomConfirmValidator |
matchPattern | CustomMatchPatterValidator |
required | CustomRequiredValidator |
Middlewares
function
decodeCurrentUser([accessTokenKey], [refreshTokenKey]) ⇒ Kind: global function
Returns: function
- Express middleware function
Param | Type | Default | Description |
---|---|---|---|
[accessTokenKey] | string |
"accessToken" |
The accessToken key |
[refreshTokenKey] | string |
"refreshToken" |
The accessToken key |
function
errorHandler([includeStackTrace]) ⇒ Kind: global function
Returns: function
- Express middleware function
Param | Type | Description |
---|---|---|
[includeStackTrace] | boolean |
Whether or not to include stack trace |
function
requireAuthentication([message]) ⇒ Kind: global function
Returns: function
- Express middleware function
Param | Type | Description |
---|---|---|
[message] | string |
The message to display to user |
function
preloadSwagger(documentation) ⇒ Kind: global function
Returns: function
- Middleware to update documentation properties
Param | Type | Description |
---|---|---|
documentation | Object |
Swagger json documentation |
function
refreshAccessToken([config]) ⇒ 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 |
function
requirePrivilege(requirements, [config]) ⇒ 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 |
function
validationResult([message]) ⇒ Kind: global function
Returns: function
- Middleware to update documentation properties
Param | Type | Description |
---|---|---|
[message] | string |
General error message to return |