Browse Source

Fix post + validation

Craig Fletcher 4 năm trước cách đây
mục cha
commit
b0248d38aa
3 tập tin đã thay đổi với 25 bổ sung2 xóa
  1. 1 0
      src/easy-api.js
  2. 21 0
      src/routes/goodbye.js
  3. 3 2
      src/routes/index.js

+ 1 - 0
src/easy-api.js

@@ -44,6 +44,7 @@ function start(routes, host = '127.0.0.1', port = 8080, dbOpts, serverOpts) {
     const server = restify.createServer(serverOpts);
     const db = dbWrapper(client);
     const setupRoute = registerRoute(db, server, logger);
+    server.use(restify.plugins.bodyParser());
 
     routes.forEach(route => {
       setupRoute(route);

+ 21 - 0
src/routes/goodbye.js

@@ -0,0 +1,21 @@
+function setup({ db, yup, log }) {
+  return {
+    type: 'post',
+    route: '/goodbye',
+    handler(req, res, next) {
+      const contentPath = ['visits', req.body.name];
+      db.get(contentPath, reply => {
+        const visits = reply >= 0 ? Number(reply) + 1 : 1;
+        log.info(`Visited by ${req.body.name}.`);
+        res.send(`hello ${req.body.name}. You have visited ${visits} times.`);
+        db.set(contentPath, visits);
+        next();
+      });
+    },
+    schema: yup.object().shape({
+      name: yup.string().required(),
+    }),
+  };
+}
+
+export default setup;

+ 3 - 2
src/routes/index.js

@@ -1,6 +1,7 @@
-import hello from "./hello.js";
+import hello from './hello.js';
+import goodbye from './goodbye.js';
 
 // re-exporting here for tidiness
-const routes = [hello];
+const routes = [hello, goodbye];
 
 export default routes;