Modifying Request and Response

As we’ve seen in the previous examples, actions get called with the request andresponse objects (named req and res in the examples) passed as parameters totheir handler functions.

The req object contains the incoming HTTP request, which might or might nothave been modified by a previous action (if actions were chained).

A handler can modify the request object in place if desired. This might beuseful when writing middleware (see below) that is used to intercept incomingrequests, modify them and pass them to the actual handlers.

While modifying the request object might not be that relevant for non-middlewareactions, modifying the response object definitely is. Modifying the responseobject is an action’s only way to return data to the caller of the action.

We’ve already seen how to set the HTTP status code, the content type, and theresult body. The res object has the following properties for these:

  • contentType: MIME type of the body as defined in the HTTP standard (e.g.text/html, text/plain, application/json, …)
  • responsecode: the HTTP status code of the response as defined in the HTTPstandard. Common values for actions that succeed are 200 or 201.Please refer to the HTTP standard for more information.
  • body: the actual response dataTo set or modify arbitrary headers of the response object, the _headers_property can be used. For example, to add a user-defined header to the response,the following code will do:
  1. res.headers = res.headers || { }; // headers might or might not be present
  2. res.headers['X-Test'] = 'someValue'; // set header X-Test to "someValue"

This will set the additional HTTP header X-Test to value someValue. Otherheaders can be set as well. Note that ArangoDB might change the case of theheader names to lower case when assembling the overall response that is sent tothe caller.

It is not necessary to explicitly set a Content-Length header for the responseas ArangoDB will calculate the content length automatically and add this headeritself. ArangoDB might also add a Connection header itself to handle HTTPkeep-alive.

ArangoDB also supports automatic transformation of the body data to anotherformat. Currently, the only supported transformations are base64-encoding andbase64-decoding. Using the transformations, an action can create a base64encoded body and still let ArangoDB send the non-encoded version, for example:

  1. res.body = 'VGhpcyBpcyBhIHRlc3Q=';
  2. res.transformations = res.transformations || [ ]; // initialize
  3. res.transformations.push('base64decode'); // will base64 decode the response body

When ArangoDB processes the response, it will base64-decode what’s in res.body_and set the HTTP header _Content-Encoding: binary. The opposite can be achievedwith the base64encode transformation: ArangoDB will then automaticallybase64-encode the body and set a Content-Encoding: base64 HTTP header.

Writing dynamic action handlers

To write your own dynamic action handlers, you must put them into modules.

Modules are a means of organizing action handlers and making them loadable underspecific names.

To start, we’ll define a simple action handler in a module /ownTest:

  1. arangosh> db._modules.save({
  2. ........> path: "/db:/ownTest",
  3. ........> content:
  4. ........> "exports.do = function(req, res, options, next) {"+
  5. ........> " res.body = 'test';" +
  6. ........> " res.responseCode = 200;" +
  7. ........> " res.contentType = 'text/plain';" +
  8. ........> "};"
  9. ........> });

Show execution results

  1. {
  2. "_id" : "_modules/9694",
  3. "_key" : "9694",
  4. "_rev" : "_ZHpYbYC--_"
  5. }

Hide execution results

This does nothing but register a do action handler in a module /ownTest. Theaction handler is not yet callable, but must be mapped to a route first. To mapthe action to the route /ourtest, execute the following command:

  1. arangosh> db._routing.save({
  2. ........> url: "/ourtest",
  3. ........> action: {
  4. ........> controller: "db://ownTest"
  5. ........> }
  6. ........> });
  7. arangosh> require("internal").reloadRouting()

Show execution results

  1. {
  2. "_id" : "_routing/9698",
  3. "_key" : "9698",
  4. "_rev" : "_ZHpYbYK--_"
  5. }

Hide execution results

Now use the browser or cURL and access http://localhost:8529/ourtest :

  1.  

Show execution results

  1. shell> curl --header 'accept: application/json' --dump - http://localhost:8529/ourtest
  2.  
  3. HTTP/1.1 200 OK
  4. content-type: text/plain
  5. x-content-type-options: nosniff
  6.  
  7. "test"

Hide execution results

You will see that the module’s do function has been executed.

A Word about Caching

Sometimes it might seem that your change do not take effect. In this case theculprit could be the routing caches:

The routing cache stores the routing information computed from the __routing_collection. Whenever you change this collection manually, you need to call

  1. arangosh> require("internal").reloadRouting()

Show execution results

  1.  

Hide execution results

in order to rebuild the cache.

Advanced Usages

For detailed information see the reference manual.

Redirects

Use the following for a permanent redirect:

  1. arangosh> db._routing.save({
  2. ........> url: "/redirectMe",
  3. ........> action: {
  4. ........> do: "@arangodb/actions/redirectRequest",
  5. ........> options: {
  6. ........> permanently: true,
  7. ........> destination: "/somewhere.else/"
  8. ........> }
  9. ........> }
  10. ........> });
  11. arangosh> require("internal").reloadRouting()

Show execution results

  1. {
  2. "_id" : "_routing/9719",
  3. "_key" : "9719",
  4. "_rev" : "_ZHpYbaO--_"
  5. }

Hide execution results

  1.  

Show execution results

  1. shell> curl --header 'accept: application/json' --dump - http://localhost:8529/redirectMe
  2.  
  3. HTTP/1.1 301 Moved Permanently
  4. content-type: text/html
  5. x-content-type-options: nosniff
  6. location: /somewhere.else/
  7.  
  8. "<html><head><title>Moved</title></head><body><h1>Moved</h1><p>This page has moved to <a href=\"/somewhere.else/\">/somewhere.else/</a>.</p></body></html>"

Hide execution results

Routing Bundles

Instead of adding all routes for package separately, you canspecify a bundle:

  1. arangosh> db._routing.save({
  2. ........> routes: [
  3. ........> {
  4. ........> url: "/url1",
  5. ........> content: "route 1"
  6. ........> },
  7. ........> {
  8. ........> url: "/url2",
  9. ........> content: "route 2"
  10. ........> },
  11. ........> {
  12. ........> url: "/url3",
  13. ........> content: "route 3"
  14. ........> }
  15. ........> ]
  16. ........> });
  17. arangosh> require("internal").reloadRouting()

Show execution results

  1. {
  2. "_id" : "_routing/9733",
  3. "_key" : "9733",
  4. "_rev" : "_ZHpYbcm--_"
  5. }

Hide execution results

  1.  

Show execution results

  1. shell> curl --header 'accept: application/json' --dump - http://localhost:8529/url2
  2.  
  3. HTTP/1.1 200 OK
  4. content-type: text/plain
  5. x-content-type-options: nosniff
  6.  
  7. "route 2"
  8. shell> curl --header 'accept: application/json' --dump - http://localhost:8529/url3
  9.  
  10. HTTP/1.1 200 OK
  11. content-type: text/plain
  12. x-content-type-options: nosniff
  13.  
  14. "route 3"

Hide execution results

The advantage is, that you can put all your routes into one documentand use a common prefix.

  1. arangosh> db._routing.save({
  2. ........> urlPrefix: "/test",
  3. ........> routes: [
  4. ........> {
  5. ........> url: "/url1",
  6. ........> content: "route 1"
  7. ........> },
  8. ........> {
  9. ........> url: "/url2",
  10. ........> content: "route 2"
  11. ........> },
  12. ........> {
  13. ........> url: "/url3",
  14. ........> content: "route 3"
  15. ........> }
  16. ........> ]
  17. ........> });
  18. arangosh> require("internal").reloadRouting()

Show execution results

  1. {
  2. "_id" : "_routing/9747",
  3. "_key" : "9747",
  4. "_rev" : "_ZHpYbeu--_"
  5. }

Hide execution results

will define the URL /test/url1, /test/url2, and /test/url3:

  1.  

Show execution results

  1. shell> curl --header 'accept: application/json' --dump - http://localhost:8529/test/url1
  2.  
  3. HTTP/1.1 200 OK
  4. content-type: text/plain
  5. x-content-type-options: nosniff
  6.  
  7. "route 1"
  8. shell> curl --header 'accept: application/json' --dump - http://localhost:8529/test/url2
  9.  
  10. HTTP/1.1 200 OK
  11. content-type: text/plain
  12. x-content-type-options: nosniff
  13.  
  14. "route 2"
  15. shell> curl --header 'accept: application/json' --dump - http://localhost:8529/test/url3
  16.  
  17. HTTP/1.1 200 OK
  18. content-type: text/plain
  19. x-content-type-options: nosniff
  20.  
  21. "route 3"

Hide execution results

Writing Middleware

Assume, you want to log every request in your namespace to the console. (if ArangoDB is runningas a daemon, this will end up in the logfile). In this case you can easily define anaction for the URL /subdirectory. This action simply logsthe requests, calls the next in line, and logs the response:

  1. arangosh> db._modules.save({
  2. ........> path: "/db:/OwnMiddlewareTest",
  3. ........> content:
  4. ........> "exports.logRequest = function (req, res, options, next) {" +
  5. ........> " console = require('console'); " +
  6. ........> " console.log('received request: %s', JSON.stringify(req));" +
  7. ........> " next();" +
  8. ........> " console.log('produced response: %s', JSON.stringify(res));" +
  9. ........> "};"
  10. ........> });

Show execution results

  1. {
  2. "_id" : "_modules/9761",
  3. "_key" : "9761",
  4. "_rev" : "_ZHpYbhO--_"
  5. }

Hide execution results

This function will now be available as db://OwnMiddlewareTest/logRequest. You need totell ArangoDB that it is should use a prefix match and that the shortest matchshould win in this case:

  1. arangosh> db._routing.save({
  2. ........> middleware: [
  3. ........> {
  4. ........> url: {
  5. ........> match: "/subdirectory/*"
  6. ........> },
  7. ........> action: {
  8. ........> do: "db://OwnMiddlewareTest/logRequest"
  9. ........> }
  10. ........> }
  11. ........> ]
  12. ........> });

Show execution results

  1. {
  2. "_id" : "_routing/9765",
  3. "_key" : "9765",
  4. "_rev" : "_ZHpYbhW--_"
  5. }

Hide execution results

When you call next() in that action, the next specific routing willbe used for the original URL. Even if you modify the URL in the requestobject req, this will not cause the next() to jump to the routingdefined for this next URL. If proceeds occurring the origin URL. However,if you use next(true), the routing will stop and request handling isstarted with the new URL. You must ensure that next(true) is nevercalled without modifying the URL in the request objectreq. Otherwise an endless loop will occur.

Now we add some other simple routings to test all this:

  1. arangosh> db._routing.save({
  2. ........> url: "/subdirectory/ourtest/1",
  3. ........> action: {
  4. ........> do: "@arangodb/actions/echoRequest"
  5. ........> }
  6. ........> });
  7. arangosh> db._routing.save({
  8. ........> url: "/subdirectory/ourtest/2",
  9. ........> action: {
  10. ........> do: "@arangodb/actions/echoRequest"
  11. ........> }
  12. ........> });
  13. arangosh> db._routing.save({
  14. ........> url: "/subdirectory/ourtest/3",
  15. ........> action: {
  16. ........> do: "@arangodb/actions/echoRequest"
  17. ........> }
  18. ........> });
  19. arangosh> require("internal").reloadRouting()

Show execution results

  1. {
  2. "_id" : "_routing/9769",
  3. "_key" : "9769",
  4. "_rev" : "_ZHpYbhm--_"
  5. }
  6. {
  7. "_id" : "_routing/9772",
  8. "_key" : "9772",
  9. "_rev" : "_ZHpYbhm--B"
  10. }
  11. {
  12. "_id" : "_routing/9775",
  13. "_key" : "9775",
  14. "_rev" : "_ZHpYbhq--_"
  15. }

Hide execution results

Then we send some curl requests to these sample routes:

  1.  

Show execution results

  1. shell> curl --header 'accept: application/json' --dump - http://localhost:8529/subdirectory/ourtest/1
  2.  
  3. HTTP/1.1 200 OK
  4. content-type: application/json; charset=utf-8
  5. x-content-type-options: nosniff
  6.  
  7. {
  8. "request" : {
  9. "authorized" : true,
  10. "user" : null,
  11. "database" : "_system",
  12. "url" : "/subdirectory/ourtest/1",
  13. "protocol" : "http",
  14. "server" : {
  15. "address" : "127.0.0.1",
  16. "port" : 16659
  17. },
  18. "client" : {
  19. "address" : "127.0.0.1",
  20. "port" : 54598,
  21. "id" : "156596609405176"
  22. },
  23. "internals" : {
  24. },
  25. "headers" : {
  26. "accept" : "application/json",
  27. "authorization" : "Basic cm9vdDo=",
  28. "connection" : "Keep-Alive",
  29. "user-agent" : "ArangoDB",
  30. "host" : "127.0.0.1",
  31. "accept-encoding" : "deflate"
  32. },
  33. "requestType" : "GET",
  34. "parameters" : {
  35. },
  36. "cookies" : {
  37. },
  38. "urlParameters" : {
  39. }
  40. },
  41. "options" : {
  42. }
  43. }
  44. shell> curl --header 'accept: application/json' --dump - http://localhost:8529/subdirectory/ourtest/2
  45.  
  46. HTTP/1.1 200 OK
  47. content-type: application/json; charset=utf-8
  48. x-content-type-options: nosniff
  49.  
  50. {
  51. "request" : {
  52. "authorized" : true,
  53. "user" : null,
  54. "database" : "_system",
  55. "url" : "/subdirectory/ourtest/2",
  56. "protocol" : "http",
  57. "server" : {
  58. "address" : "127.0.0.1",
  59. "port" : 16659
  60. },
  61. "client" : {
  62. "address" : "127.0.0.1",
  63. "port" : 54598,
  64. "id" : "156596609405176"
  65. },
  66. "internals" : {
  67. },
  68. "headers" : {
  69. "accept" : "application/json",
  70. "authorization" : "Basic cm9vdDo=",
  71. "connection" : "Keep-Alive",
  72. "user-agent" : "ArangoDB",
  73. "host" : "127.0.0.1",
  74. "accept-encoding" : "deflate"
  75. },
  76. "requestType" : "GET",
  77. "parameters" : {
  78. },
  79. "cookies" : {
  80. },
  81. "urlParameters" : {
  82. }
  83. },
  84. "options" : {
  85. }
  86. }
  87. shell> curl --header 'accept: application/json' --dump - http://localhost:8529/subdirectory/ourtest/3
  88.  
  89. HTTP/1.1 200 OK
  90. content-type: application/json; charset=utf-8
  91. x-content-type-options: nosniff
  92.  
  93. {
  94. "request" : {
  95. "authorized" : true,
  96. "user" : null,
  97. "database" : "_system",
  98. "url" : "/subdirectory/ourtest/3",
  99. "protocol" : "http",
  100. "server" : {
  101. "address" : "127.0.0.1",
  102. "port" : 16659
  103. },
  104. "client" : {
  105. "address" : "127.0.0.1",
  106. "port" : 54598,
  107. "id" : "156596609405176"
  108. },
  109. "internals" : {
  110. },
  111. "headers" : {
  112. "accept" : "application/json",
  113. "authorization" : "Basic cm9vdDo=",
  114. "connection" : "Keep-Alive",
  115. "user-agent" : "ArangoDB",
  116. "host" : "127.0.0.1",
  117. "accept-encoding" : "deflate"
  118. },
  119. "requestType" : "GET",
  120. "parameters" : {
  121. },
  122. "cookies" : {
  123. },
  124. "urlParameters" : {
  125. }
  126. },
  127. "options" : {
  128. }
  129. }

Hide execution results

and the console (and / or the logfile) will show requests and replies.Note that logging doesn’t warrant the sequence in which these lineswill appear.

Application Deployment

Using single routes or bundles can bebecome a bit messy in large applications. Kaerus has written a deployment tool in node.js.

Note that there is also Foxx for building applicationswith ArangoDB.

Common Pitfalls when using Actions

Caching

If you made any changes to the routing but the changes does not have any effectwhen calling the modified actions URL, you might have been hit by somecaching issues.

After any modification to the routing or actions, it is thus recommended tomake the changes “live” by calling the following functions from within arangosh:

  1.  

Show execution results

  1.  

Hide execution results

You might also be affected by client-side caching.Browsers tend to cache content and also redirection URLs. You might need toclear or disable the browser cache in some cases to see your changes in effect.

Data types

When processing the request data in an action, please be aware that the datatype of all query parameters is string. This is because the whole URL is astring and when the individual parts are extracted, they will also be strings.

For example, when calling the URL http:// localhost:8529/hello/world?value=5

the parameter value will have a value of (string) 5, not (number) 5.This might be troublesome if you use JavaScript’s === operator when checkingrequest parameter values.

The same problem occurs with incoming HTTP headers. When sending the followingheader from a client to ArangoDB

  1. X-My-Value: 5

then the header X-My-Value will have a value of (string) 5 and not (number) 5.

404 Not Found

If you defined a URL in the routing and the URL is accessible fine viaHTTP GET but returns an HTTP 501 (not implemented) for other HTTP methodssuch as POST, PUT or DELETE, then you might have been hit by somedefaults.

By default, URLs defined like this (simple string url attribute) areaccessible via HTTP GET and HEAD only. To make such URLs accessible viaother HTTP methods, extend the URL definition with the methods attribute.

For example, this definition only allows access via GET and HEAD:

  1. {
  2. url: "/hello/world"
  3. }

whereas this definition allows HTTP GET, POST, and PUT:

  1. arangosh> db._routing.save({
  2. ........> url: {
  3. ........> match: "/hello/world",
  4. ........> methods: [ "get", "post", "put" ]
  5. ........> },
  6. ........> action: {
  7. ........> do: "@arangodb/actions/echoRequest"
  8. ........> }
  9. ........> });
  10. arangosh> require("internal").reloadRouting()

Show execution results

  1. {
  2. "_id" : "_routing/9810",
  3. "_key" : "9810",
  4. "_rev" : "_ZHpYbmC--_"
  5. }

Hide execution results

  1.  

Show execution results

  1. shell> curl --header 'accept: application/json' --dump - http://localhost:8529/hello/world
  2.  
  3. HTTP/1.1 200 OK
  4. content-type: application/json; charset=utf-8
  5. x-content-type-options: nosniff
  6.  
  7. {
  8. "request" : {
  9. "authorized" : true,
  10. "user" : null,
  11. "database" : "_system",
  12. "url" : "/hello/world",
  13. "protocol" : "http",
  14. "server" : {
  15. "address" : "127.0.0.1",
  16. "port" : 16659
  17. },
  18. "client" : {
  19. "address" : "127.0.0.1",
  20. "port" : 54598,
  21. "id" : "156596609405176"
  22. },
  23. "internals" : {
  24. },
  25. "headers" : {
  26. "accept" : "application/json",
  27. "authorization" : "Basic cm9vdDo=",
  28. "connection" : "Keep-Alive",
  29. "user-agent" : "ArangoDB",
  30. "host" : "127.0.0.1",
  31. "accept-encoding" : "deflate"
  32. },
  33. "requestType" : "GET",
  34. "parameters" : {
  35. },
  36. "cookies" : {
  37. },
  38. "urlParameters" : {
  39. }
  40. },
  41. "options" : {
  42. }
  43. }
  44. shell> curl -X POST --header 'accept: application/json' --data-binary @- --dump - http://localhost:8529/hello/world <<EOF
  45. {hello: 'world'}
  46. EOF
  47.  
  48. HTTP/1.1 200 OK
  49. content-type: application/json; charset=utf-8
  50. x-content-type-options: nosniff
  51.  
  52. {
  53. "request" : {
  54. "authorized" : true,
  55. "user" : null,
  56. "database" : "_system",
  57. "url" : "/hello/world",
  58. "protocol" : "http",
  59. "server" : {
  60. "address" : "127.0.0.1",
  61. "port" : 16659
  62. },
  63. "client" : {
  64. "address" : "127.0.0.1",
  65. "port" : 54598,
  66. "id" : "156596609405176"
  67. },
  68. "internals" : {
  69. },
  70. "headers" : {
  71. "accept" : "application/json",
  72. "authorization" : "Basic cm9vdDo=",
  73. "content-length" : "16",
  74. "connection" : "Keep-Alive",
  75. "user-agent" : "ArangoDB",
  76. "host" : "127.0.0.1",
  77. "accept-encoding" : "deflate"
  78. },
  79. "requestType" : "POST",
  80. "requestBody" : "{hello: 'world'}",
  81. "parameters" : {
  82. },
  83. "cookies" : {
  84. },
  85. "urlParameters" : {
  86. }
  87. },
  88. "options" : {
  89. }
  90. }
  91. shell> curl -X PUT --header 'accept: application/json' --data-binary @- --dump - http://localhost:8529/hello/world <<EOF
  92. {hello: 'world'}
  93. EOF
  94.  
  95. HTTP/1.1 200 OK
  96. content-type: application/json; charset=utf-8
  97. x-content-type-options: nosniff
  98.  
  99. {
  100. "request" : {
  101. "authorized" : true,
  102. "user" : null,
  103. "database" : "_system",
  104. "url" : "/hello/world",
  105. "protocol" : "http",
  106. "server" : {
  107. "address" : "127.0.0.1",
  108. "port" : 16659
  109. },
  110. "client" : {
  111. "address" : "127.0.0.1",
  112. "port" : 54598,
  113. "id" : "156596609405176"
  114. },
  115. "internals" : {
  116. },
  117. "headers" : {
  118. "accept" : "application/json",
  119. "authorization" : "Basic cm9vdDo=",
  120. "content-length" : "16",
  121. "connection" : "Keep-Alive",
  122. "user-agent" : "ArangoDB",
  123. "host" : "127.0.0.1",
  124. "accept-encoding" : "deflate"
  125. },
  126. "requestType" : "PUT",
  127. "requestBody" : "{hello: 'world'}",
  128. "parameters" : {
  129. },
  130. "cookies" : {
  131. },
  132. "urlParameters" : {
  133. }
  134. },
  135. "options" : {
  136. }
  137. }
  138. shell> curl -X DELETE --header 'accept: application/json' --dump - http://localhost:8529/hello/world
  139.  
  140. HTTP/1.1 404 Not Found
  141. content-type: application/json; charset=utf-8
  142. x-content-type-options: nosniff
  143.  
  144. {
  145. "error" : true,
  146. "code" : 404,
  147. "errorNum" : 404,
  148. "errorMessage" : "unknown path '/hello/world'"
  149. }

Hide execution results

The former definition (defining url as an object with a match attribute)will result in the URL being accessible via all supported HTTP methods (e.g.GET, POST, PUT, DELETE, …), whereas the latter definition (providing a stringurl attribute) will result in the URL being accessible via HTTP GET andHTTP HEAD only, with all other HTTP methods being disabled. Calling a URLwith an unsupported or disabled HTTP method will result in an HTTP 404 error.