collect.ts 5.97 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 * Copyright (C) 2015 Centro de Computacao Cientifica e Software Livre
 * Departamento de Informatica - Universidade Federal do Parana
 *
 * This file is part of blendb.
 *
 * blendb is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * blendb is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with blendb.  If not, see <http://www.gnu.org/licenses/>.
 */

21
import * as express from "express";
Rafael Dias's avatar
Rafael Dias committed
22 23 24
import { Request } from "../types";
import { Source, Field } from "../../core/source";
import { EnumType } from "../../core/enumType";
25
import { DataType } from "../../common/types";
Rafael Dias's avatar
Rafael Dias committed
26

27 28 29 30 31 32
/**
 * Dictionary indexed by a type name which return a
 * validation function that returns true if the
 * objetct is a valid object of that type
 * or false otherwise.
 */
Rafael Dias's avatar
Rafael Dias committed
33 34 35
interface Valid{
    [key: string]: (value: any) => boolean;
}
36

37 38 39 40
/**
 * Constroller responsable for collect part from the API. In other
 * words, controller responsable for inserting data in BlenDB.
 */
41
export class CollectCtrl {
42 43 44 45 46 47 48
    /**
     * Route that validates and insert data.
     * @param req - Object with request information
     * @param res - Object used to create and send the response
     * @param next - Call next middleware or controller. Not used but required
     * by typescript definition of route.
     */
Rafael Dias's avatar
Rafael Dias committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
    public static write(req: Request, res: express.Response, next: express.NextFunction) {

        const validador: Valid = {
            "integer": function(value: any) {
                let test = parseInt(value, 10);
                if (test === undefined || isNaN(value) ) {
                    return false;
                }

                else {
                    return true;
                }
            },
            "float": function(value: any) {
                let test = parseFloat(value);
                if (test === undefined || isNaN(value) ) {
                    return false;
                }

                else {
                    return true;
                }
            },
            "string": function(value: any) {
                let test = typeof(value);
                if (test === "string") {
                    return true;
                }

                else{
                    return false;
                }
            },
            "date": function(value: any) {

                let test: string[] = [];
                let date = new Date(value);
                try {
                    test = date.toISOString().split("T");
                }
                catch (e) {
                    return false;
                }
                if (test[0] === value){
                    return true;
                }
                else{
                    return false;
                }

            },
            "boolean": function(value: any) {
                let test: string = value;
                test = test.toLocaleLowerCase();
                if (test === "true" || test === "false"){
                    return true;
                }

                else{
                    return false;
                }
            }
        };

        let fields: Field[] = [];
        let data: string[] = [];
        let types: string[] = [];
        let source: Source;
        let enumType: EnumType;

        const id: string = req.params.class;
        try {
            source = req.engine.getSourceByName(id);
            // If source does not exist them return error

            fields = source.fields;

            for (let i = 0; i < fields.length; i++){
                data[i] = req.body[fields[i].name];
                if (!data[i]){
                    throw new Error(
                        "The '" + fields[i].name + "' wasn't informed on json");
                }
            }

            for (let i = 0; i < fields.length; i++){
135 136
            if (fields[i].dataType !== DataType.NONE){
                if (!validador[EnumType.stringfyDataType(fields[i].dataType)](data[i]) === true){
Rafael Dias's avatar
Rafael Dias committed
137 138
                    throw new Error(
                        "The value '" +  data[i] + "' from '" + fields[i].name +
139
                        "' isn't a type " + [EnumType.stringfyDataType(fields[i].dataType)]);
Rafael Dias's avatar
Rafael Dias committed
140 141 142 143
                }

            }
            else {
144
                    enumType = req.engine.getEnumTypeByName(fields[i].enumType);
Rafael Dias's avatar
Rafael Dias committed
145 146 147 148 149 150 151 152 153 154 155
                    types = enumType.values;
                    let found: boolean = false;
                    for (let j = 0; j < types.length; j++){
                        if (data[i] === types[j]){
                        found = true;
                        break;
                        }
                    }
                    if (!found) {
                        throw new Error(
                            "The value '" +  data[i] + "' from '" + fields[i].name +
156
                            "' isn't listed on " + fields[i].enumType);
Rafael Dias's avatar
Rafael Dias committed
157 158 159 160 161 162 163 164
                    }
                }
            }
        }

        catch (e) {
            res.status(500).json({
                message: "Query execution failed: " +
165
                "Could not construct query with the parameters given.",
Rafael Dias's avatar
Rafael Dias committed
166 167
                error: e.message
             });
168 169
            return;
        }
170

Rafael Dias's avatar
Rafael Dias committed
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
        req.adapter.insertIntoSource(source, req.body, (err: Error, result: any[]) => {
            if (err) {
                res.status(500).json({
                    message: "Insertion has failed",
                    error: err
                });
                return;
            }
            else{
                res.status(200).json({message: "Data has been successfully received and stored by the server"});
                return;
            }

        });

186 187
    }
}