aboutsummaryrefslogtreecommitdiffstats
path: root/packages/connect/src/utils/orders_channel_message_parser.ts
blob: 1b6cda17b930e523e5747be43ebac008c4cc76b5 (plain) (blame)
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
34
35
36
37
import { assert } from '@0xproject/assert';
import { schemas } from '@0xproject/json-schemas';
import * as _ from 'lodash';

import { OrdersChannelMessage, OrdersChannelMessageTypes } from '../types';

import { relayerResponseJsonParsers } from './relayer_response_json_parsers';

export const ordersChannelMessageParser = {
    parse(utf8Data: string): OrdersChannelMessage {
        // parse the message
        const messageObj = JSON.parse(utf8Data);
        // ensure we have a type parameter to switch on
        const type: string = _.get(messageObj, 'type');
        assert.assert(!_.isUndefined(type), `Message is missing a type parameter: ${utf8Data}`);
        assert.isString('type', type);
        // ensure we have a request id for the resulting message
        const requestId: string = _.get(messageObj, 'requestId');
        assert.assert(!_.isUndefined(requestId), `Message is missing a requestId parameter: ${utf8Data}`);
        assert.isString('requestId', requestId);
        switch (type) {
            case OrdersChannelMessageTypes.Update: {
                assert.doesConformToSchema('message', messageObj, schemas.relayerApiOrdersChannelUpdateSchema);
                const ordersJson = messageObj.payload;
                const orders = relayerResponseJsonParsers.parseAPIOrdersJson(ordersJson);
                return _.assign(messageObj, { payload: orders });
            }
            default: {
                return {
                    type: OrdersChannelMessageTypes.Unknown,
                    requestId,
                    payload: undefined,
                };
            }
        }
    },
};