Mercurial > hg > nginx-site
diff xml/en/docs/njs/examples.xml @ 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 | 253641e268a8 |
children | ba9bfd064a61 |
line wrap: on
line diff
--- a/xml/en/docs/njs/examples.xml Tue Jan 21 15:54:31 2020 +0000 +++ b/xml/en/docs/njs/examples.xml Tue Jan 21 16:37:54 2020 +0000 @@ -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 @@ </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>