3.0.5 • Published 4 years ago

@wbc-nodejs/core v3.0.5

Weekly downloads
-
License
ISC
Repository
gitlab
Last release
4 years ago

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

ParamTypeDescription
configObjectthe cors configuration
config.whitelistArray.<string>Array of url to whitelist
config.whitelistRegExArray.<RegExp>Array of url to whitelist using matching
config.appURLstringThe application url
config.exposedHeadersArrayThe application url

CorsOptions : Object

Kind: global typedef
Properties

NameTypeDescription
credentialsbooleanThe cors credentials.
exposedHeadersArray.<string>The headers to expose
originfunctionThe origin function

jwtConfig

Kind: global constant
Properties

NameType
ACTIVATION_TOKEN_LIFESPANstring
SECRET_KEYstring
ACCESS_TOKEN_LIFESPANstring
REFRESH_TOKEN_LIFESPANstring

regExp

Kind: global constant
Properties

NameType
NUMBERRegExp
POSITIVE_NUMBERRegExp
POSITIVE_NUMBER_DECIMAL_POINTRegExp
EMAILRegExp
PHONE_NUMBERRegExp
ALPHA_NUMERICRegExp
ALPHA_NUMERIC_COMMA_DOTRegExp
ALPHA_NUMERIC_PLANERegExp
PASSWORDRegExp
URLRegExp
UUIDRegExp

Error Classes

Classes

CustomError

Kind: global class

new CustomError(message, config)

ParamType
messagestring
configObject
config.httpStatusCodenumber
config.stackTracestring
config.subCodenumber
config.reason*

RequestValidationError

Kind: global class

new RequestValidationError(message, config)

ParamType
messagestring
configObject
config.subCodenumber
config.reason*

AuthenticationError

Kind: global class

new AuthenticationError(message, config)

ParamType
messagestring
configObject
config.subCodenumber
config.reason*

AuthorizationError

Kind: global class

new AuthorizationError(message, config)

ParamType
messagestring
configObject
config.subCodenumber
config.reason*

NotFoundError

Kind: global class

new NotFoundError(message, config)

ParamType
messagestring
configObject
config.subCodenumber
config.reason*

ConflictError

Kind: global class

new ConflictError(message, config)

ParamType
messagestring
configObject
config.subCodenumber
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

ParamTypeDescription
varToCheck*variable to check its type
typestringThe type to check against

getDistinctFrequency(array) ⇒ Object

Kind: global function
Returns: Object - Frequency counter

ParamTypeDescription
arrayArray | stringThe 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

ParamTypeDescription
newEnvObjectThe new environment variable(s) as object

paginate(model) ⇒ PaginationFunction

Paginates model

Kind: global function
Returns: PaginationFunction - Function to paginate the specified model

ParamTypeDescription
modelObjectmodel to add pagination to
model.findAndCountAllfunctioninbuilt model function

removeFileExtension(fileName) ⇒ string | *

To remove extension from a file

Kind: global function
Returns: string | * - Name without extension

ParamTypeDescription
fileNamestringThe 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

ParamTypeDescription
base64stringthe 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

ParamTypeDescription
objObjectobject to pick key value pair from
acceptedKeysArray.<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

ParamTypeDescription
objObjectObject to create from
forbiddenKeysArray.<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

ParamTypeDescription
urlstringThe url to extract base domain from

getCookieDomain(req) ⇒ string

To get cookie domain

Kind: global function
Returns: string - The base domain

ParamTypeDescription
reqObjectExpress request object

getTokensFromRequest(req, config) ⇒ Object

To get tokens from request

Kind: global function
Returns: Object - Token Object

ParamTypeDescription
reqObjectExpress request object
configObjectkey to find accessToken
config.accessTokenKeystringkey to find accessToken
config.refreshTokenKeystringkey to find accessToken

setTokensToResponse(res, tokens, config) ⇒ string

To set token to response

Kind: global function
Returns: string - Referer Url

ParamTypeDescription
resObjectExpress response object
tokensObjectThe tokens to set
tokens.accessstringThe access token to set
tokens.refreshstringThe access token to set
configObjectOther configurations
config.cookieDomainstringThe domain to set the token cookies on
config.accessTokenKeystringThe key to use for accessToken
config.refreshTokenKeystringThe key to use for refreshToken
config.cookieLifeInDaysnumberThe number of days before cookie expires

normalizePort(port) ⇒ boolean | number | *

Kind: global function
Returns: boolean | number | * - Normalized port

ParamTypeDescription
portstring | numberThe port to normalize

updateQueryParams(route, params, customIdentifier) ⇒ string

Kind: global function
Returns: string - The updated url with the query params attached

ParamType
routestring
paramsObject
customIdentifierstring

base64Encode(val, urlEncode) ⇒ string

Kind: global function
Returns: string - The encoded string

ParamType
val*
urlEncodeboolean

base64Decode(val, urlEncoded) ⇒ string

Kind: global function
Returns: string - The decoded string

ParamType
val*
urlEncodedboolean

convertToSlug(text) ⇒ string | *

Kind: global function
Returns: string | * - slug

ParamType
textstring

PaginationFunction ⇒ Object

Kind: global typedef
Returns: Object - Paginated data

ParamTypeDefaultDescription
pagestring | number1page to query
limitstring | number10limit for the query
optionsObjectOptions for the model

JWT Helper

Modules

Typedefs

jwt

jwt~makeToken(user, lifeSpan) ⇒ undefined | string

To generate a jwt

Kind: inner method of jwt
Returns: undefined | string - The generated token string

ParamTypeDescription
userObjectThe user to create a token for
lifeSpanstringThe 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

ParamTypeDefaultDescription
tokenStringthe access token string
includeSignatureBooleantrueWhether 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

ParamTypeDescription
userObjectThe 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

ParamTypeDescription
refreshTokenstringthe refresh token
getUserRefreshTokenGetUser | functionFunction to get user

RefreshTokenGetUser ⇒ Object

To get user data to be used to regenerate token

Kind: global typedef
Returns: Object - the user

ParamType
idstring

App Logger

logger

Application logger

Kind: global constant
Properties

NameType
stream*
addfunction
infofunction

Response Helper

response

response~render(req, res, template, data, statusCode) ⇒ HTMLDocument

Kind: inner method of response
Returns: HTMLDocument - Full html content

ParamTypeDefaultDescription
reqObjectExpress request object
resObjectExpress response object
templateStringHttp status code for the response
dataObjectData to be return as part of response body
statusCodeNumber200Http status code for the response

response~success(res, statusCode, data, message) ⇒ JSON

Kind: inner method of response
Returns: JSON - Formatted JSON server response

ParamTypeDescription
resobjectExpress response object
statusCodeNumberHttp status code for the response
dataobjectData to be return as part of response body
messageStringMessage accompanying the response data

response~ok(res, data, message) ⇒ JSON

Kind: inner method of response
Returns: JSON - Formatted JSON server response

ParamTypeDescription
resobjectExpress response object
dataobjectData to be return as part of response body
messageStringMessage accompanying the response data

response~created(res, data, message) ⇒ JSON

Kind: inner method of response
Returns: JSON - Formatted JSON server response

ParamTypeDescription
resobjectExpress response object
dataobjectData to be return as part of response body
messageStringMessage accompanying the response data

response~redirect(res, url, code) ⇒ Null

Kind: inner method of response
Returns: Null - Null

ParamTypeDescription
resobjectExpress response object
urlStringurl to redirect to
codeNumber301 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

ParamTypeDescription
fieldNamestringThe field to validate
messagestringError message

CustomConfirmValidator ⇒ *

Kind: global typedef
Returns: * - Validation chain

ParamTypeDescription
fieldNamestringThe field to validate
benchmarkstringWhat to benchmark against
messagestringError message

CustomMatchPatterValidator ⇒ *

Kind: global typedef
Returns: * - Validation chain

ParamTypeDescription
fieldNamestringThe field to validate
patternRegExppattern to test for
messagestringError message

CustomRequiredValidator ⇒ Array

Kind: global typedef
Returns: Array - Validation chain

ParamTypeDescription
...fieldNamesstringName of the required field(s)

ValidatorInstance : Object

Kind: global typedef
Properties

NameType
emailCustomValidator
passwordCustomValidator
confirmCustomConfirmValidator
matchPatternCustomMatchPatterValidator
requiredCustomRequiredValidator

Middlewares

decodeCurrentUser(accessTokenKey, refreshTokenKey) ⇒ function

Kind: global function
Returns: function - Express middleware function

ParamTypeDefaultDescription
accessTokenKeystring"accessToken"The accessToken key
refreshTokenKeystring"refreshToken"The accessToken key

errorHandler(includeStackTrace) ⇒ function

Kind: global function
Returns: function - Express middleware function

ParamTypeDescription
includeStackTracebooleanWhether or not to include stack trace

requireAuthentication(message) ⇒ function

Kind: global function
Returns: function - Express middleware function

ParamTypeDescription
messagestringThe message to display to user

preloadSwagger(documentation) ⇒ function

Kind: global function
Returns: function - Middleware to update documentation properties

ParamTypeDescription
documentationObjectSwagger json documentation

refreshAccessToken(config) ⇒ function

Kind: global function
Returns: function - Middleware to refresh accessToken

ParamTypeDescription
configObjectConfiguration object
config.accessTokenKeystringkey to find accessToken
config.refreshTokenKeystringkey to find refreshToken
config.forceRefreshEvenIfNotExpirebooleanWhether or not to refresh even if the token has not yet expired
config.getUserRefreshTokenGetUserFunction to get user data

requirePrivilege(requirements, config) ⇒ function

Kind: global function Returns: function - Privilege checker middleware

ParamTypeDefaultDescription
requirementsObjectThe requirements
requirements.hasstring | functionChecks for this privilege
requirements.hasAllArray.<string> | functionChecks for all privilege in this array
requirements.hasAnyArray.<string> | functionChecks for any privilege in this array
configObjectother configurations
config.errorMessagestringError message to show user in case requirement not met
config.privilegeKeystring"privilegeList"Key to check privilege list in req.user

validationResult(message) ⇒ function

Kind: global function
Returns: function - Middleware to update documentation properties

ParamTypeDescription
messagestringGeneral error message to return
3.0.5

4 years ago

3.0.4

4 years ago

3.0.3

4 years ago

3.0.2

4 years ago

3.0.1

4 years ago

3.0.0

4 years ago

2.2.1

4 years ago

2.2.5

4 years ago

2.2.0

4 years ago

2.1.6

4 years ago

2.1.5

4 years ago

2.1.0

4 years ago

2.0.9

4 years ago

2.0.8

4 years ago

2.0.7

4 years ago

2.0.6

4 years ago

2.0.5

4 years ago

2.0.4

4 years ago

2.0.3

4 years ago

2.0.2

4 years ago

2.0.1

4 years ago

2.0.0

4 years ago

1.1.1

4 years ago

1.1.0

4 years ago

1.0.0

4 years ago