changeset 2483:b60e5be733cd

Added Example of promisified requests to njs.
author Yaroslav Zhuravlev <yar@nginx.com>
date Tue, 21 Jan 2020 16:37:54 +0000
parents 9bf87153b1b3
children 2aa02672d54f
files xml/en/docs/njs/examples.xml xml/ru/docs/njs/examples.xml
diffstat 2 files changed, 96 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/xml/en/docs/njs/examples.xml
+++ b/xml/en/docs/njs/examples.xml
@@ -9,7 +9,7 @@
 <article name="Examples"
         link="/en/docs/njs/examples.html"
         lang="en"
-        rev="7">
+        rev="8">
 
 <section id="helloword" name="Hello World">
 
@@ -353,4 +353,51 @@ are available as part of our
 
 </section>
 
+
+<section id="promisified_subrequest" name="Promisified Subrequest">
+
+<para>
+The example works since
+<link doc="changes.xml" id="njs0.3.8">0.3.8</link>.
+<path>nginx.conf</path>:
+<example>
+js_include promisified_subrequest.js;
+
+location /start {
+    js_content content;
+}
+
+location /auth {
+    proxy_pass http://auth_backend;
+}
+
+location /backend {
+    proxy_pass http://backend;
+}
+</example>
+</para>
+
+<para>
+<path>promisified_subrequest.js</path>:
+<example>
+function content(r) {
+   r.subrequest(r, '/auth')
+   .then(reply => JSON.parse(reply.responseBody))
+   .then(response => {
+       if (!response['token']) {
+           throw new Error("token is not available");
+       }
+       return token;
+   })
+  .then(token => {
+      r.subrequest('/backend', `token=${token}`)
+      .then(reply => r.return(reply.status, reply.responseBody));
+  })
+  .catch(_ => r.return(500));
+}
+</example>
+</para>
+
+</section>
+
 </article>
--- a/xml/ru/docs/njs/examples.xml
+++ b/xml/ru/docs/njs/examples.xml
@@ -9,7 +9,7 @@
 <article name="Примеры использования"
         link="/ru/docs/njs/examples.html"
         lang="ru"
-        rev="7">
+        rev="8">
 
 <section id="helloword" name="Hello World">
 
@@ -353,4 +353,51 @@ function num_requests(r)
 
 </section>
 
+
+<section id="promisified_subrequest" name="Подзапрос с promise">
+
+<para>
+Пример работает начиная с версии
+<link doc="changes.xml" id="njs0.3.8">0.3.8</link>.
+<path>nginx.conf</path>:
+<example>
+js_include promisified_subrequest.js;
+
+location /start {
+    js_content content;
+}
+
+location /auth {
+    proxy_pass http://auth_backend;
+}
+
+location /backend {
+    proxy_pass http://backend;
+}
+</example>
+</para>
+
+<para>
+<path>promisified_subrequest.js</path>:
+<example>
+function content(r) {
+   r.subrequest(r, '/auth')
+   .then(reply => JSON.parse(reply.responseBody))
+   .then(response => {
+       if (!response['token']) {
+           throw new Error("token is not available");
+       }
+       return token;
+   })
+  .then(token => {
+      r.subrequest('/backend', `token=${token}`)
+      .then(reply => r.return(reply.status, reply.responseBody));
+  })
+  .catch(_ => r.return(500));
+}
+</example>
+</para>
+
+</section>
+
 </article>