Created
April 4, 2018 12:50
-
-
Save mykeels/b25632799bb41614cf6edb6b8e780e1d to your computer and use it in GitHub Desktop.
Fork of https://gist.github.com/mykeels/8396f87d42a809697d08f6b6c9cd8db0 showing response interrupts in a factorial API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const express = require('express') | |
| const app = express() | |
| const storage = [] | |
| app.get('/factorial', (req, res) => { | |
| const rootUrl = (url) => req.protocol + '://' + req.get('host') + url; | |
| const id = storage.length + 1; | |
| setTimeout(() => { | |
| let sum = 1; | |
| for (let i = Number(req.query.value) || 1; i >= 1; i--) { | |
| sum *= i | |
| } | |
| storage.push(sum) | |
| if (!res.headersSent) res.json({ factorial: sum }) | |
| }, 10000) //delay for 10 seconds | |
| setTimeout(() => { | |
| if (!res.headersSent) { | |
| res.status(202).json({ | |
| location: rootUrl('/factorial/' + id) | |
| }) | |
| } | |
| }, 500) //interrupt response after 500 ms | |
| }) | |
| app.get('/factorial/:id', (req, res) => { | |
| let id = Number(req.params.id) | |
| if (!!id) { | |
| if (storage[id - 1]) { | |
| res.json({ | |
| factorial: storage[id - 1] | |
| }) | |
| } | |
| else { | |
| res.status(202).send({ message: 'please wait' }) | |
| } | |
| } | |
| }) | |
| app.listen(process.env.PORT || 3030) | |
| console.log('app is running!') | |
| module.exports = app |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment