app.nim 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import strtabs, strutils, math, algorithm
  2. import nawak_mongrel, jdump
  3. import fortunes_tmpl
  4. when defined(postgre_model):
  5. import model_postgre
  6. get "/json":
  7. var j: THello
  8. j.message = "Hello, World!"
  9. # jdump serialize the tuples of the model as json
  10. return response(jdump(j), "application/json")
  11. get "/plaintext":
  12. return response("Hello, World!", "text/plain")
  13. get "/db":
  14. let w = getWorld(random(10_000)+1)
  15. return response(jdump(w), "application/json")
  16. get "/fortunes":
  17. var fortunes = getAllFortunes()
  18. let new_fortune: TFortune =
  19. (id: 0,
  20. message: "Additional fortune added at request time.")
  21. fortunes.add new_fortune
  22. sort(fortunes, proc(x, y: TFortune): int =
  23. return cmp(x.message, y.message))
  24. return response(fortunes_tmpl(fortunes), "text/html; charset=utf-8")
  25. proc limit_queries(query_params: PStringTable): int =
  26. result = 1
  27. if query_params.hasKey("queries"):
  28. try:
  29. result = parseInt(query_params["queries"])
  30. except EInvalidValue: discard
  31. # clamp the number of queries
  32. if result < 1: result = 1
  33. elif result > 500: result = 500
  34. get "/queries":
  35. let queries = limit_queries(request.query)
  36. var world: seq[TWorld]
  37. world.newSeq(queries)
  38. for i in 0.. <queries:
  39. world[i] = getWorld random(10_000) + 1
  40. return response(jdump(world), "application/json")
  41. get "/updates":
  42. let queries = limit_queries(request.query)
  43. var world: seq[TWorld]
  44. world.newSeq(queries)
  45. for i in 0.. <queries:
  46. world[i] = getWorld(random(10_000) + 1)
  47. world[i].randomNumber = random(10_000) + 1
  48. updateWorld world[i]
  49. return response(jdump(world), "application/json")
  50. custom_page 404:
  51. # customize the content of the 404 page
  52. return response(404, """Nah, I've got nothing.<br>
  53. Here's a <b>404 Page Not Found</b> error for you.""")
  54. run(init=init_db, nb_threads=256)