webapp.js 3.9 KB
Newer Older
R
rsercano 已提交
1 2 3
/**
 * Created by Sercan on 26.10.2016.
 */
R
rsercano 已提交
4 5 6 7
import {WebApp} from "meteor/webapp";
import {Meteor} from "meteor/meteor";
import {Papa} from "meteor/harrison:papa-parse";
import {databasesBySessionId} from "/server/imports/mongodb/methods_common";
R
rsercano 已提交
8 9 10 11
import LOGGER from "/server/imports/internal/logger";

const mongodbApi = require('mongodb');

R
rsercano 已提交
12
WebApp.connectHandlers.use('/export', function (req, res) {
R
rsercano 已提交
13 14 15 16 17
    const urlParts = decodeURI(req.url).split('&');
    const format = urlParts[0].substr(urlParts[0].indexOf('=') + 1);
    const selectedCollection = urlParts[1].substr(urlParts[1].indexOf('=') + 1);
    const selector = urlParts[2].substr(urlParts[2].indexOf('=') + 1);
    const cursorOptions = urlParts[3].substr(urlParts[3].indexOf('=') + 1);
R
rsercano 已提交
18 19 20

    LOGGER.info('[export]', format, selectedCollection, selector, cursorOptions);

R
rsercano 已提交
21
    Meteor.call("find", selectedCollection, JSON.parse(selector), JSON.parse(cursorOptions), false, Meteor.default_connection._lastSessionId, function (err, result) {
R
rsercano 已提交
22 23 24 25 26
        if (err || result.error) {
            LOGGER.error('[export]', err, result.error);
            res.writeHead(400);
            res.end('Query error: ' + JSON.stringify(err) + " " + JSON.stringify(result.error));
        } else {
R
rsercano 已提交
27
            const headers = {
R
rsercano 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
                'Content-type': 'application/octet-stream',
                'Content-Disposition': 'attachment; filename=export_result.' + format
            };
            if (format === 'JSON') {
                res.writeHead(200, headers);
                res.end(JSON.stringify(result.result));
            } else if (format === 'CSV') {
                res.writeHead(200, headers);
                res.end(Papa.unparse(result.result, {delimiter: ";", newLine: "\n"}));
            } else {
                res.writeHead(400);
                res.end('Unsupported format: ' + format);
            }
        }
    });
});

R
rsercano 已提交
45 46 47

WebApp.connectHandlers.use('/healthcheck', function (req, res) {
    res.writeHead(200);
R
rsercano 已提交
48
    res.end('Server is up and running !');
R
rsercano 已提交
49 50 51
});

WebApp.connectHandlers.use("/download", function (req, res) {
R
rsercano 已提交
52 53 54
    const urlParts = decodeURI(req.url).split('&');
    let fileId = urlParts[0].substr(urlParts[0].indexOf('=') + 1);
    let bucketName = urlParts[1].substr(urlParts[1].indexOf('=') + 1);
R
rsercano 已提交
55
    let sessionId = urlParts[2].substr(urlParts[2].indexOf('=') + 1);
R
rsercano 已提交
56

R
rsercano 已提交
57
    LOGGER.info('[downloadFile]', fileId, bucketName, sessionId);
R
rsercano 已提交
58

R
#352  
rsercano 已提交
59
    res.charset = 'UTF-8';
R
rsercano 已提交
60 61 62
    if (!bucketName || !fileId) {
        LOGGER.info('[downloadFile]', 'file not found !');
        res.writeHead(400);
R
rsercano 已提交
63
        res.end('File not found !');
R
rsercano 已提交
64 65 66 67
        return;
    }

    try {
R
rsercano 已提交
68
        let filesCollection = databasesBySessionId[sessionId].collection(bucketName + '.files');
R
rsercano 已提交
69 70
        filesCollection.find({_id: new mongodbApi.ObjectId(fileId)}).limit(1).next(function (err, doc) {
            if (doc) {
R
rsercano 已提交
71
                const bucket = new mongodbApi.GridFSBucket(databasesBySessionId[sessionId], {bucketName: bucketName});
R
rsercano 已提交
72
                const headers = {
R
rsercano 已提交
73
                    'Content-type': 'application/octet-stream',
R
#352  
rsercano 已提交
74
                    'Content-Disposition': 'attachment; filename=' + encodeURIComponent(doc.filename)
R
rsercano 已提交
75
                };
R
#352  
rsercano 已提交
76
                LOGGER.info('[downloadFile]', 'file found and started downloading...', headers);
R
rsercano 已提交
77
                const downloadStream = bucket.openDownloadStream(new mongodbApi.ObjectID(fileId));
R
rsercano 已提交
78
                res.writeHead(200, headers);
R
rsercano 已提交
79
                const pipeStream = downloadStream.pipe(res);
R
rsercano 已提交
80 81 82 83 84 85 86
                pipeStream.on('finish', function () {
                    LOGGER.info('[downloadFile]', 'file has been downloaded successfully');
                });

            } else {
                LOGGER.info('[downloadFile]', 'file not found !');
                res.writeHead(400);
R
rsercano 已提交
87
                res.end('File not found !');
R
rsercano 已提交
88 89 90 91 92 93
            }
        });
    }
    catch (ex) {
        LOGGER.error('[downloadFile]', ex);
        res.writeHead(500);
R
rsercano 已提交
94
        res.end('Unexpected error: ' + ex.message);
R
rsercano 已提交
95 96 97
    }

});