Bug:Fix file validation issue
[vnfsdk/refrepo.git] / vnfmarket / src / main / webapp / vnfmarket / node_modules / http-proxy / examples / helpers / store.js
1
2 //
3 // just to make these example a little bit interesting, 
4 // make a little key value store with an http interface
5 // (see couchbd for a grown-up version of this)
6 //
7 // API:
8 // GET / 
9 // retrive list of keys
10 //
11 // GET /[url]
12 // retrive object stored at [url]
13 // will respond with 404 if there is nothing stored at [url]
14 //
15 // POST /[url]
16 // 
17 // JSON.parse the body and store it under [url]
18 // will respond 400 (bad request) if body is not valid json.
19 //
20 // TODO: cached map-reduce views and auto-magic sharding.
21 //
22 var Store = module.exports = function Store () {
23   this.store = {};
24 };
25
26 Store.prototype = {
27   get: function (key) {
28     return this.store[key]
29   },
30   set: function (key, value) {
31     return this.store[key] = value
32   },
33   handler:function () {
34     var store = this
35     return function (req, res) {
36       function send (obj, status) {
37         res.writeHead(200 || status,{'Content-Type': 'application/json'})
38         res.write(JSON.stringify(obj) + '\n')
39         res.end()
40       }
41       var url = req.url.split('?').shift()
42       if (url === '/') {
43         console.log('get index')
44         return send(Object.keys(store.store))
45       } else if (req.method == 'GET') {
46         var obj = store.get (url)
47         send(obj || {error: 'not_found', url: url}, obj ? 200 : 404)
48       } else {
49         //post: buffer body, and parse.
50         var body = '', obj
51         req.on('data', function (c) { body += c})
52         req.on('end', function (c) {
53           try {
54             obj = JSON.parse(body)
55           } catch (err) {
56             return send (err, 400)
57           }
58           store.set(url, obj)
59           send({ok: true})
60         })
61       } 
62     }
63   }
64 }