@@ -2,21 +2,30 @@ local cjson = require "cjson.safe"
22
33local _M = {}
44
5+ local function parseDuration (str )
6+ -- TODO: parse inputs like "1h", "2d", "10m" and return them as seconds
7+ return 5 * 60
8+ end
9+
510function _M .init ()
611 local npmConfig = ngx .shared .npmConfig
7- local registry = os.getenv (" npm_config_registry" ):gsub (" /+$" , " " )
8- local pattern = registry :gsub (" %." , " %%." ):gsub (" %-" , " %%-" )
12+ _M .registry = os.getenv (" npm_config_registry" ):gsub (" /+$" , " " )
13+ _M .hostPattern = _M .registry :gsub (" %." , " %%." ):gsub (" %-" , " %%-" )
14+ _M .MAXAGE = parseDuration (os.getenv (" MAXAGE" ) or " 5m" )
915 -- escape . and - which have special meaning in Lua patterns
10- npmConfig :set (' npm_config_registry' , registry )
11- npmConfig :set (' npm_upstream_pattern' , pattern )
16+ npmConfig :set (' npm_config_registry' , _M .registry )
17+ npmConfig :set (' npm_upstream_pattern' , _M .hostPattern )
18+ npmConfig :set (' MAXAGE' , _M .MAXAGE )
1219end
1320
1421function _M .getPackage ()
1522 local uri = ngx .var .uri
1623 local meta = ngx .shared .npmMeta
1724 local body = meta :get (uri )
25+ local base = ngx .var .scheme .. ' ://' .. ngx .var .http_host
1826 -- yep, our own shared memory cache implementation :-/
1927 if body == nil then
28+ ngx .var .ephemeralCacheStatus = ' MISS'
2029 local res = ngx .location .capture (' /-@-' .. uri ,
2130 { copy_all_vars = true })
2231 body = res .body
@@ -27,19 +36,13 @@ function _M.getPackage()
2736 -- next time
2837 return ngx .redirect (uri , ngx .HTTP_MOVED_TEMPORARILY )
2938 end
30- meta :set (uri , body )
39+ meta :set (uri , body , _M .MAXAGE )
40+ else
41+ ngx .var .ephemeralCacheStatus = ' HIT'
3142 end
43+ body = string.gsub (body , _M .hostPattern , base )
3244 ngx .header [" Content-Length" ] = # body
3345 ngx .print (body )
3446end
3547
36- function _M .filterPackageBody ()
37- local npmConfig = ngx .shared .npmConfig
38- local upstream = npmConfig :get (' npm_upstream_pattern' )
39- -- need to construct URL because we may be proxying http<->https
40- local base = ngx .var .scheme .. ' ://' .. ngx .var .http_host
41- -- ngx.log(ngx.ERR, "Modifying JSON of " .. ngx.var.uri .. " to replace '" .. upstream .. "' with '" .. base .. "'")
42- ngx .arg [1 ] = string.gsub (ngx .arg [1 ], upstream , base )
43- end
44-
4548return _M
0 commit comments