diff options
author | braxtonhall | 2022-10-23 20:19:25 +0000 |
---|---|---|
committer | braxtonhall | 2022-10-23 20:19:25 +0000 |
commit | d860ca6e3ca4a3a5b32d127691a36c58ef17d3e4 (patch) | |
tree | 0fb1fc3783f4bb6a1faa9293060575156c48ca52 /entries/braxtonhall/express/index.js | |
parent | 093dafb774cf566736e4c060e3b89f2c1e0f4005 (diff) |
Implement express fib
Diffstat (limited to 'entries/braxtonhall/express/index.js')
-rw-r--r-- | entries/braxtonhall/express/index.js | 28 |
1 files changed, 16 insertions, 12 deletions
diff --git a/entries/braxtonhall/express/index.js b/entries/braxtonhall/express/index.js index 2da6092..117a04b 100644 --- a/entries/braxtonhall/express/index.js +++ b/entries/braxtonhall/express/index.js @@ -1,22 +1,26 @@ -import { get } from "axios"; +import axios from "axios"; import express from "express"; +const PORT = 3000; + const app = express(); -const getURL = (n) => `/fib?${new URLSearchParams({n})}`; +const {get} = axios.create({baseURL: `http://localhost:${PORT}`}); + +const getFib = (n) => get("/fib", {params: {n}}).then(({data}) => data); -app.get("/fib", async (res, req, next) => { - const {n} = req.params; - if (n <= 0) { - res.send(n).status(200); +app.get("/fib", async (req, res, next) => { + const n = Number(req.query.n); + + if (!isFinite(n) || n < 0) { + res.status(400).json("`n` must be a natural number"); + } else if (n <= 1) { + res.status(200).json(n); } else { - const futures = [get(getURL(n - 1)), get(getURL(n - 2))]; - const [nSub1, nSub2] = await Promise.all(futures); - res.send(nSub1 + nSub2).status(200); + const [nSub1, nSub2] = await Promise.all([getFib(n - 1), getFib(n - 2)]); + res.status(200).json(nSub1 + nSub2); } return next(); }); -app.start(); - -// TODO... is this syntax correct??? +app.listen(PORT); |