all files / lib/html-parsers/ simple-code-action.js

100% Statements 2/2
100% Branches 4/4
100% Functions 2/2
100% Lines 2/2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33                                                             
'use strict'
 
import JsonStream from 'JSONStream'
 
/**
 * Returns a JSON parser that will expect 'code' attribute to interpret it.
 *
 * This parser understands the following values:
 * - OK, and responds with self.status = 'ok'
 * - KO, and responds with self.status = 'ko'
 * - other values triggers an 'error' event from the parser.
 *
 * @param  {MyfoxWrapperApiCommon}  wrapperApi  The Api instance, to throw events
 * @return {JsonStream}             The JsonStream parser to plug on the json stream.
 */
export default function (wrapperApi) {
  // Receive {"code":"OK"} OR {"code":"KO","msg":[["...","error"]]}
  const parser = JsonStream.parse('code')
  parser.on('data', (data) => {
    if (data === 'KO') {
      parser.status = 'ko'
    } else if (data === 'OK') {
      parser.status = 'ok'
    } else {
      const error = new Error('Unknown format returned by Myfox.')
      error.status = 500
      parser.emit('error', error)
    }
  })
  return parser
}