diff --git a/docs/classes/RateLimitError.html b/docs/classes/RateLimitError.html index d6542a9..73903da 100644 --- a/docs/classes/RateLimitError.html +++ b/docs/classes/RateLimitError.html @@ -1,4 +1,4 @@ -RateLimitError | @brainspore/hypernexus

Hierarchy (View Summary)

Constructors

constructor +RateLimitError | @brainspore/hypernexus

Hierarchy (View Summary)

Constructors

Properties

Methods

Constructors

Properties

cause?: unknown
data?: any
message: string
name: string
retryAfter?: number
stack?: string
statusCode?: number
timeout?: number
prepareStackTrace?: (err: Error, stackTraces: CallSite[]) => any

Optional override for formatting stack traces

+

Constructors

Properties

cause?: unknown
data?: any
message: string
name: string
retryAfter?: number
stack?: string
statusCode?: number
timeout?: number
prepareStackTrace?: (err: Error, stackTraces: CallSite[]) => any

Optional override for formatting stack traces

stackTraceLimit: number

Methods

  • Create .stack property on a target object

    Parameters

    • targetObject: object
    • OptionalconstructorOpt: Function

    Returns void

diff --git a/docs/classes/TimeoutError.html b/docs/classes/TimeoutError.html index 667ea8c..3ad5ddb 100644 --- a/docs/classes/TimeoutError.html +++ b/docs/classes/TimeoutError.html @@ -1,4 +1,4 @@ -TimeoutError | @brainspore/hypernexus

Hierarchy (View Summary)

Constructors

constructor +TimeoutError | @brainspore/hypernexus

Hierarchy (View Summary)

Constructors

Properties

Methods

Constructors

Properties

cause?: unknown
data?: any
message: string
name: string
stack?: string
statusCode?: number
timeout?: number
prepareStackTrace?: (err: Error, stackTraces: CallSite[]) => any

Optional override for formatting stack traces

+

Constructors

Properties

cause?: unknown
data?: any
message: string
name: string
stack?: string
statusCode?: number
timeout?: number
prepareStackTrace?: (err: Error, stackTraces: CallSite[]) => any

Optional override for formatting stack traces

stackTraceLimit: number

Methods

  • Create .stack property on a target object

    Parameters

    • targetObject: object
    • OptionalconstructorOpt: Function

    Returns void

diff --git a/docs/classes/Transport.html b/docs/classes/Transport.html index 71e0b99..36283d8 100644 --- a/docs/classes/Transport.html +++ b/docs/classes/Transport.html @@ -16,7 +16,7 @@

When a request fails

When rate limit is exceeded

When request times out

-

Constructors

Constructors

Methods

Constructors

Methods

  • Parameters

    • middleware: (
          config: AxiosRequestConfig,
      ) => AxiosRequestConfig<any> | Promise<AxiosRequestConfig<any>>

    Returns void

  • Executes multiple HTTP requests in parallel or sequentially

    +

Constructors

Methods

  • Parameters

    • middleware: (
          config: AxiosRequestConfig,
      ) => AxiosRequestConfig<any> | Promise<AxiosRequestConfig<any>>

    Returns void

  • Parameters

    • endpoint: string
    • Optionaloptions: RequestOptions

    Returns void

  • Makes a POST request to a codeunit endpoint with optional payload and request options

    +
  • Parameters

    • endpoint: string
    • Optionaloptions: RequestOptions

    Returns void

  • Makes a POST request to a codeunit endpoint with optional payload and request options

    Type Parameters

    • T

      The expected response type

    Parameters

    • codeunit: string

      The codeunit endpoint URL

    • Optionalpayload: any

      Optional request payload/body data

    • Optionaloptions: RequestOptions

      Optional request configuration options

    Returns Promise<T>

    Promise that resolves with the response data

    When the request fails with status code 500

    -
  • Type Parameters

    • T

    Parameters

    • endpoint: string
    • Optionalpayload: any
    • Optionaloptions: RequestOptions

    Returns Promise<T>

  • Creates an OData filter query string from the provided parameters

    +
  • Type Parameters

    • T

    Parameters

    • endpoint: string
    • Optionalpayload: any
    • Optionaloptions: RequestOptions

    Returns Promise<T>

  • Creates an OData filter query string from the provided parameters

    Parameters

    • params: Record<string, any>

      An object containing key-value pairs to be converted into filter conditions

    Returns undefined | object

    An object with the '$filter' property containing the generated OData filter string, or undefined if no valid parameters

    When there is an error preparing the BC 365 filter query

    @@ -57,4 +57,4 @@
    filter({ name: "John", age: 30 })
    // Returns: { $filter: "name eq 'John' and age eq 30" }
    -
  • Type Parameters

    • T

    Parameters

    • endpoint: string
    • OptionalqueryParams: Record<string, any>
    • Optionaloptions: RequestOptions

    Returns Promise<T>

  • Type Parameters

    • T

    Parameters

    • endpoint: string
    • Optionalpayload: any
    • Optionaloptions: RequestOptions

    Returns Promise<T>

  • Type Parameters

    • T

    Parameters

    • endpoint: string
    • Optionalpayload: any
    • Optionaloptions: RequestOptions

    Returns Promise<T>

  • Type Parameters

    • T

    Parameters

    • endpoint: string
    • Optionalpayload: any
    • Optionaloptions: RequestOptions

    Returns Promise<T>

+
diff --git a/docs/classes/TransportError.html b/docs/classes/TransportError.html index c0e975c..9308651 100644 --- a/docs/classes/TransportError.html +++ b/docs/classes/TransportError.html @@ -1,4 +1,4 @@ -TransportError | @brainspore/hypernexus

Hierarchy (View Summary)

Constructors

constructor +TransportError | @brainspore/hypernexus

Hierarchy (View Summary)

Constructors

Properties

Methods

Constructors

Properties

cause?: unknown
data?: any
message: string
name: string
stack?: string
statusCode?: number
prepareStackTrace?: (err: Error, stackTraces: CallSite[]) => any

Optional override for formatting stack traces

+

Constructors

Properties

cause?: unknown
data?: any
message: string
name: string
stack?: string
statusCode?: number
prepareStackTrace?: (err: Error, stackTraces: CallSite[]) => any

Optional override for formatting stack traces

stackTraceLimit: number

Methods

  • Create .stack property on a target object

    Parameters

    • targetObject: object
    • OptionalconstructorOpt: Function

    Returns void

diff --git a/docs/functions/CreateAuthHandler.html b/docs/functions/CreateAuthHandler.html index 464b444..9d02e1e 100644 --- a/docs/functions/CreateAuthHandler.html +++ b/docs/functions/CreateAuthHandler.html @@ -1,2 +1,2 @@ CreateAuthHandler | @brainspore/hypernexus

Function CreateAuthHandler

  • Create AuthHandler Factory

    -

    Parameters

    • type: AuthTypes
    • credentials: Credentials
    • oath2Config: null | OAuth2Config = null
    • accesTokenURL: null | string = null
    • redisConfig: null | RedisConfig = null

    Returns AuthHandler

+

Parameters

Returns AuthHandler

diff --git a/docs/functions/getConfig.html b/docs/functions/getConfig.html index 3b46ac0..c4410ca 100644 --- a/docs/functions/getConfig.html +++ b/docs/functions/getConfig.html @@ -1,2 +1,2 @@ getConfig | @brainspore/hypernexus

Get EnvConfig

-
+
diff --git a/docs/variables/transport-1.html b/docs/variables/transport-1.html index 34fa412..1ae3caf 100644 --- a/docs/variables/transport-1.html +++ b/docs/variables/transport-1.html @@ -1 +1 @@ -transport | @brainspore/hypernexus

Variable transportConst

transport: Transport = ...
+transport | @brainspore/hypernexus

Variable transportConst

transport: Transport = ...
diff --git a/index.ts b/index.ts index 11af0e4..3a8091e 100644 --- a/index.ts +++ b/index.ts @@ -4,6 +4,7 @@ import { getConfig } from "./src/config/env.js"; import { TransportError } from "./src/errors/TransportError.js"; import { RateLimitError } from "./src/errors/RateLimitError.js"; import { TimeoutError } from "./src/errors/TimeoutError.js"; +import { modifyRequestCompanyConfig } from "./src/interfaces/middleware/ModifyRequestCompanyInformation.js"; @@ -18,73 +19,28 @@ const authHandler = CreateAuthHandler(authType, credentials, oath2Config, access // Initialize the transport utility const transport = new Transport({ baseURL, cacheTTL: 600 }, authHandler); -transport.addMiddleware(async (config) => { - const token = await authHandler.getAccessToken(); - if (!token) return config; - if (!config.headers) { - config.headers = {}; - } - config.headers['Authorization'] = `Bearer ${token}`; - return config; -}); -transport.addMiddleware(async (config) => { - const company = config?.headers?.['X-Custom-Request-Company']; - const whichCompanyIdentifier = config?.headers?.['X-Custom-Request-Company-Identifier']; - config.headers = config.headers ?? {} - if (company) { - if (whichCompanyIdentifier) { - switch (whichCompanyIdentifier) { - case 'Company-Name': { - config.params = config.params ?? {}; - config.params.company = company; - config.headers['X-Custom-Params-Company-Command'] = 'Skip' - break; - }; - case 'Company-Id': { - const splittedUrl = config?.url?.split("/"); - if (splittedUrl && Array.isArray(splittedUrl)) { - const last = splittedUrl[splittedUrl.length - 1]; - const url = `${splittedUrl.slice(0, -1).join("/")}/companies(${company})/${last}`; - config.url = url; - config.headers = config.headers ?? {} - config.headers['X-Custom-Params-Company-Command'] = 'Remove' - } - break; - }; - default: { - config.headers['X-Custom-Params-Company-Command'] = 'Set' - } - } - } - } else { - if (whichCompanyIdentifier) { - switch (whichCompanyIdentifier) { - case 'Company-Name': { - config.params = config.params ?? {}; - config.params.company = companyName; - config.headers['X-Custom-Params-Company-Command'] = 'Skip' - break; - }; - case 'Company-Id': { - const splittedUrl = config?.url?.split("/") - if (splittedUrl && Array.isArray(splittedUrl)) { - const last = splittedUrl[splittedUrl.length - 1]; - const url = `${splittedUrl.slice(0, -1).join("/")}/companies(${companyId})/${last}`; - config.url = url; - config.headers = config.headers ?? {} - config.headers['X-Custom-Params-Company-Command'] = 'Remove' - } - break; - }; - default: { - config.headers['X-Custom-Params-Company-Command'] = 'Set' - } - } +if (authType === 'oauth2' && !oath2Config && !accessTokenURL && !redisConfig) { + throw new Error("[OAuth2]: Invalid OAuth2 configuration in the environment file.", { + cause: 'Invalid Configuration', + }); +} + +if (authType === 'oauth2') { + transport.addMiddleware(async (config) => { + const token = await authHandler.getAccessToken(); + if (!token) return config; + if (!config.headers) { + config.headers = {}; } - } - return config; -}); + config.headers['Authorization'] = `Bearer ${token}`; + return config; + }); +} + +transport.addMiddleware(modifyRequestCompanyConfig({ companyName, companyId })); + + export { Transport, CreateAuthHandler, diff --git a/package.json b/package.json index 0002cb5..aef1df7 100644 --- a/package.json +++ b/package.json @@ -19,17 +19,12 @@ "release:minor": "zx release.js --minor", "release:major": "zx release.js --major" }, - "keywords": [ - "Windows Authentication", - "Nodejs", - "Network Transport Wrapper" - ], + "keywords": ["Windows Authentication", "Nodejs", "Network Transport Wrapper"], "author": "Paullaster Okoth", "license": "MIT", "description": "A lightWeight, robust and easily extensible HTTP(/2,/3)/HTTPS network transport utility", "devDependencies": { "@eslint/js": "^9.20.0", - "@types/express": "^5.0.3", "@types/node": "^22.13.1", "eslint": "^9.20.0", "globals": "^15.14.0", @@ -45,14 +40,11 @@ "axios": "^1.7.9", "axios-ntlm": "^1.4.3", "bottleneck": "^2.19.5", - "bullmq": "^5.61.0", "dotenv": "^16.4.7", "ioredis": "^5.8.1", "node-cache": "^5.1.2", "pino": "^9.6.0", "pino-pretty": "^13.0.0" }, - "files": [ - "dist" - ] + "files": ["dist"] } diff --git a/src/interfaces/middleware/ModifyRequestCompanyInformation.ts b/src/interfaces/middleware/ModifyRequestCompanyInformation.ts new file mode 100644 index 0000000..800130a --- /dev/null +++ b/src/interfaces/middleware/ModifyRequestCompanyInformation.ts @@ -0,0 +1,60 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +import { AxiosRequestConfig } from "axios"; + +export const modifyRequestCompanyConfig = (environmentConf: { companyName: string | undefined; companyId: string | undefined }) => (config: AxiosRequestConfig) => { + const company = config?.headers?.['X-Custom-Request-Company'] ?? config?.headers?.['x-custom-request-company']; + const whichCompanyIdentifier = config?.headers?.['X-Custom-Request-Company-Identifier'] ?? config?.headers?.['X-Custom-Request-Company-Identifier']; + config.headers = config.headers ?? {} + if (company) { + if (whichCompanyIdentifier) { + switch (whichCompanyIdentifier) { + case 'Company-Name': { + config.params = config.params ?? {}; + config.params.company = company; + config.headers['X-Custom-Params-Company-Command'] = 'Skip' + break; + }; + case 'Company-Id': { + const splittedUrl = config?.url?.split("/"); + if (splittedUrl && Array.isArray(splittedUrl)) { + const last = splittedUrl[splittedUrl.length - 1]; + const url = `${splittedUrl.slice(0, -1).join("/")}/companies(${company})/${last}`; + config.url = url; + config.headers = config.headers ?? {} + config.headers['X-Custom-Params-Company-Command'] = 'Remove' + } + break; + }; + default: { + config.headers['X-Custom-Params-Company-Command'] = 'Set' + } + } + } + } else { + if (whichCompanyIdentifier) { + switch (whichCompanyIdentifier) { + case 'Company-Name': { + config.params = config.params ?? {}; + config.params.company = environmentConf.companyName; + config.headers['X-Custom-Params-Company-Command'] = 'Skip' + break; + }; + case 'Company-Id': { + const splittedUrl = config?.url?.split("/") + if (splittedUrl && Array.isArray(splittedUrl)) { + const last = splittedUrl[splittedUrl.length - 1]; + const url = `${splittedUrl.slice(0, -1).join("/")}/companies(${environmentConf.companyId})/${last}`; + config.url = url; + config.headers = config.headers ?? {} + config.headers['X-Custom-Params-Company-Command'] = 'Remove' + } + break; + }; + default: { + config.headers['X-Custom-Params-Company-Command'] = 'Set' + } + } + } + } + return config; +} \ No newline at end of file diff --git a/src/transport/Transport.ts b/src/transport/Transport.ts index ef4335d..06cf0ac 100644 --- a/src/transport/Transport.ts +++ b/src/transport/Transport.ts @@ -117,6 +117,8 @@ export class Transport { this.logger.debug({ url: config.url, method: config.method, params: config.params }, 'Outgoing requests'); if (config.params) { config.params = { ...config.params }; + } else { + config.params = {}; } config.headers = config.headers ?? {}; const companyParamCommand = config.headers['X-Custom-Params-Company-Command'];