main.swift 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import Vapor
  2. import JSON
  3. import HTTP
  4. import VaporPostgreSQL
  5. import TfbCommon
  6. let drop = Droplet()
  7. try drop.addProvider(VaporPostgreSQL.Provider.self)
  8. // All test types require `Server` and `Date` HTTP response headers.
  9. // Vapor has standard middleware that adds `Date` header.
  10. // We use custom middleware that adds `Server` header.
  11. drop.middleware.append(ServerMiddleware())
  12. // Normally we would add preparation for Fluent Models.
  13. // `drop.preparations.append(World.self)` etc.
  14. // During preparation Fluent creates `fluent` table to track migrations.
  15. // But TFB environment does not grant user rights to create tables.
  16. // So we just configure our Models with correct database.
  17. World.database = drop.database
  18. Fortune.database = drop.database
  19. // Test type 1: JSON serialization
  20. drop.get("json") { req in
  21. return try JSON(node: Message("Hello, World!"))
  22. }
  23. // Test type 2: Single database query
  24. drop.get("db") { _ in
  25. let worldId = WorldMeta.randomId()
  26. return try World.find(worldId)?.makeJSON() ?? JSON(node: .null)
  27. }
  28. // Test type 3: Multiple database queries
  29. drop.get("queries") { req in
  30. let queries = queriesParam(for: req)
  31. let ids = (1...queries).map({ _ in WorldMeta.randomId() })
  32. let worlds = try ids.flatMap { try World.find($0)?.makeJSON() }
  33. return JSON(worlds)
  34. }
  35. // Test type 4: Fortunes
  36. drop.get("fortunes") { _ in
  37. let fortunes = try Fortune.all().flatMap { try $0.makeNode() }
  38. return try drop.view.make("fortune", ["fortunes": Node(fortunes)])
  39. }
  40. // Test type 5: Database updates
  41. drop.get("updates") { req in
  42. let queries = queriesParam(for: req)
  43. let ids = (1...queries).map({ _ in WorldMeta.randomId() })
  44. var worlds = try ids.flatMap { try World.find($0) }
  45. worlds.forEach { $0.randomNumber = WorldMeta.randomRandomNumber() }
  46. worlds = try worlds.flatMap { world in
  47. var modifiedWorld = world
  48. try modifiedWorld.save()
  49. return modifiedWorld
  50. }
  51. let updatedWorlds = try worlds.flatMap { try $0.makeJSON() }
  52. return JSON(updatedWorlds)
  53. }
  54. // Test type 6: Plaintext
  55. let helloWorldBuffer = "Hello, World!".utf8.array
  56. drop.get("plaintext") { req in
  57. return Response(headers: ["Content-Type": "text/plain; charset=utf-8"], body: helloWorldBuffer)
  58. }
  59. drop.run()