|
| 1 | +-- http-api.lua -- |
| 2 | +local httpd |
| 3 | +local json = require('json') |
| 4 | + |
| 5 | +local function validate(cfg) |
| 6 | + if cfg.host then |
| 7 | + assert(type(cfg.host) == "string", "'host' should be a string containing a valid IP address") |
| 8 | + end |
| 9 | + if cfg.port then |
| 10 | + assert(type(cfg.port) == "number", "'port' should be a number") |
| 11 | + assert(cfg.port >= 1 and cfg.port <= 65535, "'port' should be between 1 and 65535") |
| 12 | + end |
| 13 | +end |
| 14 | + |
| 15 | +local function apply(cfg) |
| 16 | + if httpd then |
| 17 | + httpd:stop() |
| 18 | + end |
| 19 | + httpd = require('http.server').new(cfg.host, cfg.port) |
| 20 | + local response_headers = { ['content-type'] = 'application/json' } |
| 21 | + httpd:route({ path = '/band/:id', method = 'GET' }, function(req) |
| 22 | + local id = req:stash('id') |
| 23 | + local band_tuple = box.space.bands:get(tonumber(id)) |
| 24 | + if not band_tuple then |
| 25 | + return { status = 404, body = 'Band not found' } |
| 26 | + else |
| 27 | + local band = { id = band_tuple['id'], |
| 28 | + band_name = band_tuple['band_name'], |
| 29 | + year = band_tuple['year'] } |
| 30 | + return { status = 200, headers = response_headers, body = json.encode(band) } |
| 31 | + end |
| 32 | + end) |
| 33 | + httpd:route({ path = '/band', method = 'GET' }, function(req) |
| 34 | + local limit = req:query_param('limit') |
| 35 | + if not limit then |
| 36 | + limit = 5 |
| 37 | + end |
| 38 | + local band_tuples = box.space.bands:select({}, { limit = tonumber(limit) }) |
| 39 | + local bands = {} |
| 40 | + for _, tuple in pairs(band_tuples) do |
| 41 | + local band = { id = tuple['id'], |
| 42 | + band_name = tuple['band_name'], |
| 43 | + year = tuple['year'] } |
| 44 | + table.insert(bands, band) |
| 45 | + end |
| 46 | + return { status = 200, headers = response_headers, body = json.encode(bands) } |
| 47 | + end) |
| 48 | + httpd:start() |
| 49 | +end |
| 50 | + |
| 51 | +local function stop() |
| 52 | + httpd:stop() |
| 53 | +end |
| 54 | + |
| 55 | +local function init() |
| 56 | + require('data'):add_sample_data() |
| 57 | +end |
| 58 | + |
| 59 | +init() |
| 60 | + |
| 61 | +return { |
| 62 | + validate = validate, |
| 63 | + apply = apply, |
| 64 | + stop = stop, |
| 65 | +} |
0 commit comments