File size: 2,035 Bytes
56b6519
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
function Custom(res, status, code, message) {
  res.status(code).json({ status: status, datas: message });
}
exports.Custom = Custom;

/*
 *** Codes 2xx ***
 */

function Ok(res, data) {
  res.status(200).json({ status: 'success', datas: data });
}
exports.Ok = Ok;

function Created(res, data) {
  res.status(201).json({ status: 'success', datas: data });
}
exports.Created = Created;

function NoContent(res, data) {
  res.status(204).json({ status: 'success', datas: data });
}
exports.NoContent = NoContent;

function SendFile(res, filename, file) {
  res.set({ 'Content-Disposition': `attachment; filename="${filename}"` });
  res.status(200).send(file);
}
exports.SendFile = SendFile;

function SendImage(res, image) {
  res.set({ 'Content-Type': 'image/png', 'Content-Length': image.length });
  res.status(200).send(image);
}
exports.SendImage = SendImage;

/*
 *** Codes 4xx ***
 */

function BadRequest(res, error) {
  res.status(400).json({ status: 'error', datas: error });
}
exports.BadRequest = BadRequest;

function NotFound(res, error) {
  res.status(404).json({ status: 'error', datas: error });
}
exports.NotFound = NotFound;

function BadParameters(res, error) {
  res.status(422).json({ status: 'error', datas: error });
}
exports.BadParameters = BadParameters;

function Unauthorized(res, error) {
  res.status(401).json({ status: 'error', datas: error });
}
exports.Unauthorized = Unauthorized;

function Forbidden(res, error) {
  res.status(403).json({ status: 'error', datas: error });
}
exports.Forbidden = Forbidden;

/*
 *** Codes 5xx ***
 */

function Internal(res, error) {
  if (error.fn) var fn = exports[error.fn];
  if (typeof fn === 'function') fn(res, error.message);
  else if (error.errmsg) {
    res.status(500).json({ status: 'error', datas: error.errmsg });
  } else if (error.message)
    res.status(500).json({ status: 'error', datas: error.message });
  else {
    console.log(error);
    res.status(500).json({ status: 'error', datas: 'Internal Error' });
  }
}
exports.Internal = Internal;