app.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. const express = require('express');
  2. const sdt = require('silly-datetime');
  3. const app = express();
  4. const PORT = 1523;
  5. app.use(express.json());
  6. var balance = 0;
  7. // 消费
  8. app.post("/purchase", (req, res) => {
  9. const value = parseFloat(req.body.amount);
  10. if (isNaN(value) || !isFinite(req.body.amount)) {
  11. res.status(400).send(JSON.stringify({code: -102, message: "Illegal data", data: {balance: balance}}));
  12. return;
  13. }
  14. if(value < 0) {
  15. res.status(400).send(JSON.stringify({code: -101, message: "Amount must be positive.", data: null}));
  16. } else {
  17. if (balance - value < 0) {
  18. res.status(200).send(JSON.stringify({code: 101, message: "Insufficient balance.", data: null}));
  19. return;
  20. }
  21. balance -= value;
  22. res.status(200).send(JSON.stringify({code: 0, message: "purchased", data: {balance: balance}}));
  23. }
  24. });
  25. // 充值
  26. app.post("/recharge", (req, res) => {
  27. const value = parseFloat(req.body.amount);
  28. if (isNaN(value) || !isFinite(req.body.amount)) {
  29. res.status(400).send(JSON.stringify({code: -102, message: "Illegal data", data: null}));
  30. return;
  31. }
  32. balance += value;
  33. res.status(200).send(JSON.stringify({code: 0, message: "recharged", data: {balance: balance}}));
  34. });
  35. app.get("/balance", (req, res) => {
  36. res.status(200).send(JSON.stringify({code: 0, message: "success", data: {balance: balance}}))
  37. });
  38. app.listen(PORT, () => console.log(`Listening on port ${PORT}`));