File

lib/common/xml-data-bridge/xml-data-bridge.middleware.ts

Description

Middleware for parsing XML data from requests.

Index

Properties
Methods

Methods

Private parseXMLFromRequest
parseXMLFromRequest(req: Request)

Parses XML data from the request.

Parameters :
Name Type Optional Description
req Request No
  • The request object.
Returns : Promise<object>

A promise that resolves to the parsed XML data.

Async use
use(req: Request, res: Response, next: NextFunction)

Parses XML data from the request and modifies the request body.

Parameters :
Name Type Optional Description
req Request No
  • The request object.
res Response No
  • The response object.
next NextFunction No
  • The next function to call.
Returns : any

Properties

Private Readonly parser
Default value : Xdb.getXmlParser()
import { Injectable, NestMiddleware } from "@nestjs/common";
import { NextFunction, Request, Response } from "express";
import { Xdb } from "./xml-data-bridge.constants";

/**
 * Middleware for parsing XML data from requests.
 */
@Injectable()
export class XmlDataBridgeMiddleware implements NestMiddleware {
  private readonly parser = Xdb.getXmlParser();

  /**
   * Parses XML data from the request and modifies the request body.
   * @param req - The request object.
   * @param res - The response object.
   * @param next - The next function to call.
   */
  async use(req: Request, res: Response, next: NextFunction) {
    if (req.headers["content-type"] === "application/xml") {
      req.body = await this.parseXMLFromRequest(req);
      req.body = Xdb.parseXmlBody(req.body);
    }
    next();
  }

  /**
   * Parses XML data from the request.
   * @param req - The request object.
   * @returns A promise that resolves to the parsed XML data.
   */
  private parseXMLFromRequest(req: Request): Promise<object> {
    return new Promise((resolve, reject) => {
      let xmlData = "";
      req.on("data", (chunk) => {
        xmlData += chunk;
      });
      req.on("end", () => {
        this.parser.parseString(xmlData, (err, result) => {
          if (err) {
            reject(err);
          } else {
            resolve(result as object);
          }
        });
      });
    });
  }
}

results matching ""

    No results matching ""