2018-08-09 12:09:28 +02:00
/ * *
* @ author Matt C [ matt @ artemisbot . uk ]
* @ copyright Crown Copyright 2018
* @ license Apache - 2.0
* /
2019-07-09 13:23:59 +02:00
import Operation from "../Operation.mjs" ;
import OperationError from "../errors/OperationError.mjs" ;
2018-08-09 12:09:28 +02:00
import notepack from "notepack.io" ;
2019-07-09 13:23:59 +02:00
import { isWorkerEnvironment } from "../Utils.mjs" ;
2018-08-09 12:09:28 +02:00
/ * *
* To MessagePack operation
* /
class ToMessagePack extends Operation {
/ * *
* ToMessagePack constructor
* /
constructor ( ) {
super ( ) ;
this . name = "To MessagePack" ;
this . module = "Code" ;
2018-08-21 20:29:19 +02:00
this . description = "Converts JSON to MessagePack encoded byte buffer. MessagePack is a computer data interchange format. It is a binary form for representing simple data structures like arrays and associative arrays." ;
this . infoURL = "https://wikipedia.org/wiki/MessagePack" ;
2018-08-09 12:09:28 +02:00
this . inputType = "JSON" ;
this . outputType = "ArrayBuffer" ;
this . args = [ ] ;
}
/ * *
* @ param { JSON } input
* @ param { Object [ ] } args
* @ returns { ArrayBuffer }
* /
run ( input , args ) {
try {
2019-07-05 11:17:52 +02:00
if ( isWorkerEnvironment ( ) ) {
2018-08-20 20:08:01 +02:00
return notepack . encode ( input ) ;
} else {
2019-01-01 20:19:07 +01:00
const res = notepack . encode ( input ) ;
// Safely convert from Node Buffer to ArrayBuffer using the correct view of the data
return ( new Uint8Array ( res ) ) . buffer ;
2018-08-20 20:08:01 +02:00
}
2018-08-09 12:09:28 +02:00
} catch ( err ) {
throw new OperationError ( ` Could not encode JSON to MessagePack: ${ err } ` ) ;
2018-08-20 20:08:01 +02:00
}
2018-08-09 12:09:28 +02:00
}
}
export default ToMessagePack ;