all files / api/lib/ schema.js

96% Statements 24/25
87.5% Branches 7/8
100% Functions 1/1
96% Lines 24/25
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53                14×                                          
'use strict';
 
const hl = require('highland');
const fs = hl.streamifyAll(require('fs'));
const path = require('path');
const R = require('ramda');
const restify = require("restify");
 
const refReplace = R.curry(function(schemasURL, schemaString) {
    const ref = R.head(R.match(/"\$ref":\s?"[^"]*"/g, schemaString));
    const contentType = !R.isNil(ref) ? R.head(R.match(/\/\w*/g, ref)) : '';
    if (R.isNil(ref)) {
        return schemaString;
    }
    return refReplace(schemasURL, schemaString.replace(ref, '\"ref\": \"' + schemasURL + contentType + '\"'));
});
 
module.exports = {
    getSchemaList: (req, res, next) => {
        const schemasURL = `http://${req.headers.host}/schemas/`;
        return fs.readdirStream(path.resolve('schemas'))
            .sequence()
            .map(fileName => [fileName.replace('.json', ''), `${schemasURL}${fileName.replace('.json', '')}`])
            .collect()
            .map(R.fromPairs)
            .toCallback((err, result) => {
                Iif (err) {
                    next(new restify.InternalServerError(err));
                } else {
                    res.charSet('utf-8');
                    res.send(result);
                }
            });
    },
    getSchema: (req, res, next) => {
        const schemasURL = `http://${req.headers.host}/schemas`;
        return fs.readFileStream(path.resolve(`schemas/${req.params.contentType}.json`), 'utf8')
            .map(R.pipe(
                refReplace(schemasURL),
                R.replace(/\"ref\"\:/g, '\"\$ref\"\:'),
                JSON.parse
            ))
            .toCallback((err, result) => {
                if (err) {
                    next(new restify.ResourceNotFoundError('No schema found'));
                } else {
                    res.charSet('utf-8');
                    res.send(result);
                }
            });
    }
};