12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- const express = require('express');
- const sdt = require('silly-datetime');
- const app = express();
- const PORT = 1523;
- app.use(express.json());
- var balance = 0;
- // 消费
- app.post("/purchase", (req, res) => {
- const value = parseFloat(req.body.amount);
- if (isNaN(value) || !isFinite(req.body.amount)) {
- res.status(400).send(JSON.stringify({code: -102, message: "Illegal data", data: {balance: balance}}));
- return;
- }
- if(value < 0) {
- res.status(400).send(JSON.stringify({code: -101, message: "Amount must be positive.", data: null}));
- } else {
- if (balance - value < 0) {
- res.status(200).send(JSON.stringify({code: 101, message: "Insufficient balance.", data: null}));
- return;
- }
- balance -= value;
- res.status(200).send(JSON.stringify({code: 0, message: "purchased", data: {balance: balance}}));
- }
- });
- // 充值
- app.post("/recharge", (req, res) => {
- const value = parseFloat(req.body.amount);
- if (isNaN(value) || !isFinite(req.body.amount)) {
- res.status(400).send(JSON.stringify({code: -102, message: "Illegal data", data: null}));
- return;
- }
- balance += value;
- res.status(200).send(JSON.stringify({code: 0, message: "recharged", data: {balance: balance}}));
- });
- app.get("/balance", (req, res) => {
- res.status(200).send(JSON.stringify({code: 0, message: "success", data: {balance: balance}}))
- });
- app.listen(PORT, () => console.log(`Listening on port ${PORT}`));
|