Skip to content

Instantly share code, notes, and snippets.

@dholth
Last active August 29, 2015 14:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dholth/62ccd920be0a80a51443 to your computer and use it in GitHub Desktop.
Save dholth/62ccd920be0a80a51443 to your computer and use it in GitHub Desktop.
get many documents from couchdb, stream to a single response
local cjson = require 'cjson'
local forward_headers = ngx.req.get_headers()
local body = ngx.req.read_body()
local query_args = ngx.req.get_query_args() -- then json-decode all the values
local post_args = ngx.req.get_body_data()
local db = ngx.var.db
for k, v in pairs(query_args) do
query_args[k] = cjson.decode(v)
end
local json = cjson.decode(post_args)
ngx.header.content_type = 'application/json'
-- don't want attachments as mime
ngx.req.set_header('accept', 'application/json')
ngx.say('[')
for i,v in ipairs(json.docs) do
local id = v['id']
local args = {}
v['id'] = nil
-- combine query string arguments and per-item arguments
for k,v in pairs(query_args) do
args[k] = v
end
for k,v in pairs(v) do
args[k] = v
end
local subreq = ngx.location.capture('/db/' .. db .. '/' .. id, {args=args})
ngx.say(subreq.body)
if i < #json.docs then
ngx.say(',')
end
end
ngx.say(']')
# nginx reverse proxy config including new lua-powered endpoint
lua_code_cache off; # for debug only
location ~ ^/db/(.*)/_new_endpoint$ {
set $db $1;
content_by_lua_file 'dbproxy.lua';
}
location /db {
rewrite /db/(.*) /$1 break;
proxy_buffering off;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Host $proxy_host;
proxy_pass http://localhost:5984;
proxy_redirect http://localhost:5984 http://$host/db;
}
import requests, json
data = json.dumps({'docs':[{'id':'foo'}, {'id':'bar'}, {'id':'quux', meta=False}]})
requests.post('http://localhost/db/pouch/_new_endpoint?meta=true&open_revs="all"&revs_info=true', data=data).json()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment