AvroToJSON.mjs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. * @author jarrodconnolly [jarrod@nestedquotes.ca]
  3. * @copyright Crown Copyright 2019
  4. * @license Apache-2.0
  5. */
  6. import Operation from "../Operation.mjs";
  7. import OperationError from "../errors/OperationError.mjs";
  8. import avro from "avsc";
  9. /**
  10. * Avro to JSON operation
  11. */
  12. class AvroToJSON extends Operation {
  13. /**
  14. * AvroToJSON constructor
  15. */
  16. constructor() {
  17. super();
  18. this.name = "Avro to JSON";
  19. this.module = "Serialise";
  20. this.description = "Converts Avro encoded data into JSON.";
  21. this.infoURL = "https://wikipedia.org/wiki/Apache_Avro";
  22. this.inputType = "ArrayBuffer";
  23. this.outputType = "string";
  24. this.args = [
  25. {
  26. name: "Force Valid JSON",
  27. type: "boolean",
  28. value: true
  29. }
  30. ];
  31. }
  32. /**
  33. * @param {ArrayBuffer} input
  34. * @param {Object[]} args
  35. * @returns {string}
  36. */
  37. run(input, args) {
  38. if (input.byteLength <= 0) {
  39. throw new OperationError("Please provide an input.");
  40. }
  41. const forceJSON = args[0];
  42. return new Promise((resolve, reject) => {
  43. const result = [];
  44. const inpArray = new Uint8Array(input);
  45. const decoder = new avro.streams.BlockDecoder();
  46. decoder
  47. .on("data", function (obj) {
  48. result.push(obj);
  49. })
  50. .on("error", function () {
  51. reject(new OperationError("Error parsing Avro file."));
  52. })
  53. .on("end", function () {
  54. if (forceJSON) {
  55. resolve(result.length === 1 ? JSON.stringify(result[0], null, 4) : JSON.stringify(result, null, 4));
  56. } else {
  57. const data = result.reduce((result, current) => result + JSON.stringify(current) + "\n", "");
  58. resolve(data);
  59. }
  60. });
  61. decoder.write(inpArray);
  62. decoder.end();
  63. });
  64. }
  65. }
  66. export default AvroToJSON;