Response.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. var error = require("./Errors");
  2. module.exports = class Response {
  3. constructor(code, msg, data)
  4. {
  5. this.code=0;
  6. this.message="Success";
  7. this.data=null;
  8. if(code!=undefined) this.code=code;
  9. if(code!=undefined) this.message=msg;
  10. if(data!=undefined) this.data=data;
  11. }
  12. getCode() {return this.code;}
  13. getMessage() {return this.message;}
  14. getData() {return this.data;}
  15. setCode(c){ this.code = c; }
  16. setMessage(c){ this.message = c; }
  17. setData(c){ this.data = c; }
  18. toString()
  19. {
  20. return JSON.stringify(this);
  21. }
  22. static fromError(code, data)
  23. {
  24. var msg = error.messages[code][0];
  25. var r = new Response(code, msg, data)
  26. if(data==undefined) delete r.data;
  27. return r;
  28. }
  29. static writeResponse(res, err, data)
  30. {
  31. res.setHeader("Content-Type", "application/json");
  32. console.log("1 : "+err);
  33. res.status(error.messages[err][1]);
  34. res.end(JSON.stringify(Response.fromError(err, data)));
  35. if(error.messages[err][1]>=400) return null;
  36. return true;
  37. }
  38. //std error
  39. static success(data) { return Response.fromError(error.ESUCCESS, data); }
  40. static noent(data) { return Response.fromError(error.ENOENT, data); }
  41. static perm(data) { return Response.fromError(error.EPERM, data); }
  42. static badArgs(data) { return Response.fromError(error.EINVAL, data);}
  43. static badUser(data) { return Response.fromError(error.BAD_USER, data); }
  44. static userExists(data) { return Response.fromError(error.USER_EXISTS, data); }
  45. static badProject(data) { return Response.fromError(error.BAD_PROJECT, data); }
  46. static projectExists(data) { return Response.fromError(error.PROJECT_EXISTS, data); }
  47. static badRes(data) { return Response.fromError(error.BAD_RES, data); }
  48. static resExists(data) { return Response.fromError(error.RES_EXISTS, data); }
  49. }