summaryrefslogtreecommitdiff
path: root/src/app/db/service/base/response.js
blob: a4bac609f0e028d2be7684e8fa25d00c44d79fc8 (plain)
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
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
/**
 * Service API responses
 * @module app/db/service/base/response
 */

import { zipCSVs, stringifyCSV, sanitizeCSV } from "app/utils/file_utils";
import debugModule from "debug";

/**
 * Debug logger
 */
const debug = debugModule("shoebox:service");

/**
 * Middleware to return the response as JSON or CSV
 */
export async function sendResponse(request, response) {
  if (response.locals.csv) {
    if (response.locals.csv.files) {
      await sendCSVZipResponse(response);
    } else {
      await sendCSVResponse(response);
    }
  } else {
    await sendJSONResponse(response);
  }
}

/**
 * Respond with a ZIP file containing multiple CSVs
 * @param  {Response} response  the response object
 */
async function sendCSVZipResponse(response) {
  const zipData = await zipCSVs(response.locals.csv.files);
  response.set("Content-Type", "application/zip");
  response.set(
    "Content-Disposition",
    `attachment; filename=${response.locals.csv.filename}`
  );
  response.set("Content-Length", zipData.length);
  response.set("Access-Control-Expose-Headers", "Content-Disposition");
  response.write(zipData, "binary");
  response.end(null, "binary");
}

/**
 * Respond with a single CSV
 * @param  {Response} response  the response object
 */
async function sendCSVResponse(response) {
  const csvData = await stringifyCSV(sanitizeCSV(response.locals.csv.data));
  response.set("Content-Type", "text/csv; charset=utf-8");
  response.set(
    "Content-Disposition",
    `attachment; filename=${response.locals.csv.filename}`
  );
  response.set("Content-Length", csvData.length);
  response.set("Access-Control-Expose-Headers", "Content-Disposition");
  response.send(csvData);
}

/**
 * Respond with JSON
 * @param  {Response} response  the response object
 */
async function sendJSONResponse(response) {
  response.json(response.locals);
}

/**
 * Error-handling middleware
 * @param  {Error}            error    an error object
 * @param  {express.request}  request  the request object
 * @param  {express.response} response the response object
 * @param  {function}         next     function to proceed to the next middleware
 */
export function handleError(error, request, response, next) {
  const { errors } = request.service.options;
  debug("Error", error.name, error.message);
  let message;

  if (errors) {
    Object.keys(errors).some((key) => {
      if (error.message.match(key)) {
        message = errors[key];
        return true;
      }
      return false;
    });
    if (message) {
      response.status(403).send({ code: 403, error: message });
      return;
    }
  }

  if (error.name === "UnauthorizedError") {
    debug("Unauthorized");
    response.status(401).send({ code: 401, error: error.message });
  } else if (error.message === "EmptyResponse") {
    debug("Not found");
    response.status(404).send({ code: 404, error: error.message });
  } else if (error.message === "UserNotActive") {
    debug("User not active");
    response.status(401).send({ code: 401, error: error.message });
  } else if (error.message === "PermissionsError") {
    debug("Insufficient permissions");
    response.status(401).send({ code: 401, error: error.message });
  } else {
    debug("Unexpected error");
    // debug(error);
    response.status(403).send({
      code: 403,
      error: error.name || error.message,
      message: error.message,
    });
    next();
  }
}