import express from 'express'
import logger from 'morgan'
import wga from 'wga'

let app = express()
app.use(logger('dev', {
  skip: (req, res) => res.statusCode < 400
}))

let config = {
  totalPosts: 200
}
let concurrencyCount = 0

function sleep(ms = 0) {
  return new Promise(r => setTimeout(r, ms))
}

app.get('/posts', (req, res) => {
  res.setHeader('Content-Type', 'application/json')
  let posts = []
  for (let i = 0; i < config.totalPosts; i++) {
    posts.push('/posts/' + (i + 1))
  }
  res.send(JSON.stringify(posts, null, 2))
})

app.get('/posts/:postid', wga(async (req, res) => {
  let id = parseInt(req.params.postid)
  concurrencyCount++
  if (id >= 1 && id <= config.totalPosts) {
    let sleepMs = parseInt((Math.random() * 10000000) % 1000)
    console.log(`current concurrency: ${concurrencyCount}, url: ${req.url}, sleep ${sleepMs}`)
    await sleep(sleepMs)
    res.send('Best article in the world, no: ' + req.params.postid)
  } else {
    res.status(404).send('post not found')
  }
  concurrencyCount--
}))

export default app

@@ -198,16 +198,79 @@
 sts: 200
+,%0A  maxConcurrency: 10,%0A  minWaitTime: 500,%0A  maxWaitTime: 1000
 %0A%7D%0Alet c
@@ -363,16 +363,507 @@
 ms))%0A%7D%0A%0A
+app.get('/config', (req, res) =%3E %7B%0A  res.setHeader('Content-Type', 'application/json')%0A  res.send(JSON.stringify(config, null, 2))%0A%7D)%0A%0Aapp.post('/config/:key/:value', (req, res) =%3E %7B%0A  let intValue = parseInt(req.params.value)%0A  if (config.hasOwnProperty(req.params.key) && !isNaN(intValue)) %7B%0A    config%5Breq.params.key%5D = intValue%0A    res.setHeader('Content-Type', 'application/json')%0A    res.send(JSON.stringify(config, null, 2))%0A  %7D else %7B%0A    res.status(401).send('bad request')%0A  %7D%0A%7D)%0A%0A
 app.get(
@@ -1183,16 +1183,134 @@
 postid)%0A
+  if (concurrencyCount == config.maxConcurrency) %7B%0A    res.status(429).send('max concurrency reached')%0A    return%0A  %7D%0A
   concur
@@ -1397,41 +1397,86 @@
 Int(
-(Math.random() * 10000000) %25 1000
+config.minWaitTime + Math.random() * (config.maxWaitTime - config.minWaitTime)
 )%0A  

add more feature in server