[d24f17c] | 1 | import stampit from 'stampit';
|
---|
| 2 | import { ParseResultElement, StringElement } from '@swagger-api/apidom-core';
|
---|
| 3 | import ParserError from "../../../errors/ParserError.mjs";
|
---|
| 4 | import Parser from "../Parser.mjs";
|
---|
| 5 | /**
|
---|
| 6 | * Everything that is not recognized by other parsers will be considered by this parser
|
---|
| 7 | * as a binary data and will be encoded to Base64 format.
|
---|
| 8 | */
|
---|
| 9 | const BinaryParser = stampit(Parser, {
|
---|
| 10 | props: {
|
---|
| 11 | name: 'binary'
|
---|
| 12 | },
|
---|
| 13 | methods: {
|
---|
| 14 | async canParse(file) {
|
---|
| 15 | const hasSupportedFileExtension = this.fileExtensions.length === 0 ? true : this.fileExtensions.includes(file.extension);
|
---|
| 16 | return hasSupportedFileExtension;
|
---|
| 17 | },
|
---|
| 18 | async parse(file) {
|
---|
| 19 | try {
|
---|
| 20 | /**
|
---|
| 21 | * More information about binary strings and btoa function in following link:
|
---|
| 22 | * https://developer.mozilla.org/en-US/docs/Web/API/btoa
|
---|
| 23 | *
|
---|
| 24 | * @example
|
---|
| 25 | * ArrayBuffer to base64 conversion:
|
---|
| 26 | *
|
---|
| 27 | * const binaryString = String.fromCharCode.apply(null, file.data);
|
---|
| 28 | * base64String = btoa(binaryString);
|
---|
| 29 | */
|
---|
| 30 | const binaryString = unescape(encodeURIComponent(file.toString()));
|
---|
| 31 | const base64String = btoa(binaryString);
|
---|
| 32 | const parseResultElement = new ParseResultElement();
|
---|
| 33 | if (base64String.length !== 0) {
|
---|
| 34 | const base64StringElement = new StringElement(base64String);
|
---|
| 35 | base64StringElement.classes.push('result');
|
---|
| 36 | parseResultElement.push(base64StringElement);
|
---|
| 37 | }
|
---|
| 38 | return parseResultElement;
|
---|
| 39 | } catch (error) {
|
---|
| 40 | throw new ParserError(`Error parsing "${file.uri}"`, {
|
---|
| 41 | cause: error
|
---|
| 42 | });
|
---|
| 43 | }
|
---|
| 44 | }
|
---|
| 45 | }
|
---|
| 46 | });
|
---|
| 47 | export default BinaryParser; |
---|