xml2js#Parser TypeScript Examples

The following examples show how to use xml2js#Parser. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: convert-xml-to-json-object.ts    From barista with Apache License 2.0 6 votes vote down vote up
export function convertXmlToJsonObject(xml: string) {
  return new Promise<any>((resolve, reject) => {
    const logger = new Logger('ConvertXmlToJsonObject');
    try {
      const parser = new Parser({ explicitArray: false });
      parser.parseString(xml, (err, result) => {
        if (err) {
          reject(err);
        } else if (result) {
          resolve(result);
        } else {
          const message = `convertXmlToJsonObject() [No err or result returned]\n[${xml}}]`;
          this.logger.error(message);
          reject({ message });
        }
      });
    } catch (error) {
      this.logger.error(`convertXmlToJsonObject() error: ${error}\n[${xml}}]`);
      reject(error);
    }
  });
}
Example #2
Source File: Connection.ts    From huawei-lte-api-ts with GNU Lesser General Public License v3.0 6 votes vote down vote up
private async processResponseXml(response: AxiosResponse): Promise<Record<string, unknown>> {
        // In some cases unsupported methods, e.g. in config namespace,
        // respond with a redirect to the home page, which may not
        // parse as XML (even though it's labeled XHTML). Try to detect
        // such cases, and return a generated "not supported" error
        // instead of letting the XML parse error pass through.

        const xml = response.data;

        if (!xml) {
            return {}
        }

        const parser = new Parser({explicitArray : false});

        try {
            return await parser.parseStringPromise(xml)
        } catch (error) {
            if (response.request.responseURL != response.request.url) {
                return {
                    'error': {
                        'code': ResponseCodeEnum.ERROR_SYSTEM_NO_SUPPORT,
                        'message': ''
                    }
                }
            }
            throw error
        }
    }
Example #3
Source File: error-handler.service.ts    From worktez with MIT License 6 votes vote down vote up
parseXML(data: any) {
    return new Promise(resolve => {
      var k: string | number,
        arr = [],
        parser = new Parser(
          {
            trim: true,
            explicitArray: true
          });
      parser.parseString(data, function (err, result) {
        var obj = result.Component;
        for (k in obj.SubComponent) {
          var item = obj.SubComponent[k];
          arr.push(item)
        }
        resolve(arr);
      });
    });
  }
Example #4
Source File: bbb.ts    From backend with MIT License 6 votes vote down vote up
export async function startBBBMeeting(meeting: BBBMeeting) {
    const callName = 'create';
    const params = {
        attendeePW: meeting.attendeePW,
        meetingID: meeting.meetingID,
        moderatorPW: meeting.moderatorPW,
        name: meeting.meetingName,
        record: "false"
    };
    const queryParams = new URLSearchParams(params).toString(); //use URLSearchParams to have correct encoding which also encodes "'" correctly as required by application/x-www-form-urlencoded format (which BBB seems to use and require)

    const response = await axios.get(`${baseUrl}${callName}?${queryParams}&checksum=${hashToken(callName + queryParams + sharedSecret, "sha1")}`, {
        headers: {
            //explicitly use application/xml such that the server will respond with xml always (for some reaseon the BBB server supports json responses only if the request failed, but not if the request was successful)
            accept: "application/xml"
        }
    });
    if (response.status !== 200) {
        //response level error (for example network error, server crash...)
        throw new Error("Status code: " + response.status);
    }

    //in case of a successful *BBB* response, it always contains a returncode, which must be SUCCESS
    const parsedResponseData = await (new Parser({
        explicitArray: false //do not put all child nodes into an array automatically...
    })).parseStringPromise(response.data);

    if (parsedResponseData.response?.returncode !== "SUCCESS") {
        logger.error(`An error occurred during creation of the BBB meeting (meetingID: ${meeting.meetingID}). Error: ${parsedResponseData.response.message}`);
        throw new Error(`Meeting with id '${meeting.meetingID}' couldn't be started!`);
        //TODO: improve error handling – also for the other calls (and refactor this whole thing here...)
    }
}
Example #5
Source File: bbb.ts    From backend with MIT License 5 votes vote down vote up
parser = new Parser()
Example #6
Source File: withFacebookAndroid-test.ts    From react-native-fbsdk-next with MIT License 4 votes vote down vote up
describe('Android facebook config', () => {
  it(`returns null from all getters if no value provided`, () => {
    expect(getFacebookScheme({})).toBe(null);
    expect(getFacebookAppId({})).toBe(null);
    expect(getFacebookDisplayName({})).toBe(null);
    expect(getFacebookAutoLogAppEvents({})).toBe(null);
    expect(getFacebookAutoInitEnabled({})).toBe(null);
    expect(getFacebookAdvertiserIDCollection({})).toBe(null);
  });

  it(`returns correct value from all getters if value provided`, () => {
    expect(getFacebookScheme({scheme: 'fbmyscheme'})).toMatch('fbmyscheme');
    expect(getFacebookAppId({appID: 'my-app-id'})).toMatch('my-app-id');
    expect(getFacebookDisplayName({displayName: 'my-display-name'})).toMatch(
      'my-display-name',
    );
    expect(getFacebookAutoLogAppEvents({autoLogAppEventsEnabled: false})).toBe(
      false,
    );
    expect(getFacebookAutoInitEnabled({isAutoInitEnabled: true})).toBe(true);
    expect(
      getFacebookAdvertiserIDCollection({
        advertiserIDCollectionEnabled: false,
      }),
    ).toBe(false);
  });

  it('adds scheme, appid, display name, autolog events, auto init, advertiser id collection to androidmanifest.xml', async () => {
    let androidManifestJson = await readAndroidManifestAsync(
      sampleManifestPath,
    );
    const facebookConfig = {
      appID: 'my-app-id',
      scheme: 'fbmyscheme',
      displayName: 'my-display-name',
      autoLogAppEventsEnabled: false,
      isAutoInitEnabled: true,
      advertiserIDCollectionEnabled: false,
    };
    androidManifestJson = setFacebookConfig(
      facebookConfig,
      androidManifestJson,
    );
    // Run this twice to ensure copies don't get added.
    androidManifestJson = setFacebookConfig(
      facebookConfig,
      androidManifestJson,
    );

    const mainApplication = getMainApplication(androidManifestJson);
    if (!mainApplication) {
      throw new Error('Could not find main application');
    }

    const facebookActivity = mainApplication.activity?.filter(
      (e) => e.$['android:name'] === 'com.facebook.CustomTabActivity',
    );
    expect(facebookActivity).toHaveLength(1);

    const applicationId = mainApplication['meta-data']?.filter(
      (e) => e.$['android:name'] === 'com.facebook.sdk.ApplicationId',
    );
    expect(applicationId).toHaveLength(1);
    expect(applicationId?.[0].$['android:value']).toMatch(
      '@string/facebook_app_id',
    );

    const displayName = mainApplication['meta-data']?.filter(
      (e) => e.$['android:name'] === 'com.facebook.sdk.ApplicationName',
    );
    expect(displayName).toHaveLength(1);
    expect(displayName?.[0].$['android:value']).toMatch(
      facebookConfig.displayName,
    );

    const autoLogAppEventsEnabled = mainApplication['meta-data']?.filter(
      (e) => e.$['android:name'] === 'com.facebook.sdk.AutoLogAppEventsEnabled',
    );
    expect(autoLogAppEventsEnabled).toHaveLength(1);
    expect(autoLogAppEventsEnabled?.[0].$['android:value']).toMatch(
      facebookConfig.autoLogAppEventsEnabled.toString(),
    );

    const advertiserIDCollectionEnabled = mainApplication['meta-data']?.filter(
      (e) =>
        e.$['android:name'] ===
        'com.facebook.sdk.AdvertiserIDCollectionEnabled',
    );
    expect(advertiserIDCollectionEnabled).toHaveLength(1);
    expect(advertiserIDCollectionEnabled?.[0].$['android:value']).toMatch(
      facebookConfig.advertiserIDCollectionEnabled.toString(),
    );

    const autoInitEnabled = mainApplication['meta-data']?.filter(
      (e) => e.$['android:name'] === 'com.facebook.sdk.AutoInitEnabled',
    );
    expect(autoInitEnabled).toHaveLength(1);
    expect(autoInitEnabled?.[0].$['android:value']).toMatch(
      facebookConfig.isAutoInitEnabled.toString(),
    );
  });

  it('removes scheme, appid, display name, autolog events, auto init, advertiser id collection to androidmanifest.xml', async () => {
    const parser = new Parser();
    let androidManifestJson = await parser.parseStringPromise(filledManifest);

    const facebookConfig = {};
    androidManifestJson = setFacebookConfig(
      facebookConfig,
      androidManifestJson,
    );

    const mainApplication = getMainApplication(androidManifestJson);
    if (!mainApplication) {
      throw new Error('Could not find main application');
    }

    const facebookActivity = mainApplication.activity?.filter(
      (e) => e.$['android:name'] === 'com.facebook.CustomTabActivity',
    );
    expect(facebookActivity).toHaveLength(0);
    const applicationId = mainApplication['meta-data']?.filter(
      (e) => e.$['android:name'] === 'com.facebook.sdk.ApplicationId',
    );
    expect(applicationId).toHaveLength(0);

    const displayName = mainApplication['meta-data']?.filter(
      (e) => e.$['android:name'] === 'com.facebook.sdk.ApplicationName',
    );
    expect(displayName).toHaveLength(0);

    const autoLogAppEventsEnabled = mainApplication['meta-data']?.filter(
      (e) => e.$['android:name'] === 'com.facebook.sdk.AutoLogAppEventsEnabled',
    );
    expect(autoLogAppEventsEnabled).toHaveLength(0);

    const advertiserIDCollectionEnabled = mainApplication['meta-data']?.filter(
      (e) =>
        e.$['android:name'] ===
        'com.facebook.sdk.AdvertiserIDCollectionEnabled',
    );
    expect(advertiserIDCollectionEnabled).toHaveLength(0);

    const autoInitEnabled = mainApplication['meta-data']?.filter(
      (e) => e.$['android:name'] === 'com.facebook.sdk.AutoInitEnabled',
    );
    expect(autoInitEnabled).toHaveLength(0);
  });
});