'use strict'

const http   = require('http'),
      URL    = require('url'),
      mydb   = require('./lib/mydb'),
      Query  = require('./lib/query'),
      extend = require('util')._extend

exports.createServer = function(options) {
  options = extend({}, options)

  let db = mydb(options.db)

  return http.createServer((req, res) => {
    let url = URL.parse(req.url, true),
        query = Query(url)

    function finish(error, result) {
      if (error) {
        res.writeHead(500)
        res.end(error.toString())
      }
      else {
        res.end(JSON.stringify(result))
      }
    }

    function receive(req, next) {
      let chunks = []
      req.on('data', (chunk) => {
        chunks.push(chunk)
      })
      req.on('end', () => {
        let data = Buffer.concat(chunks)
        if (next) next(null, data)
      })
      req.on('error', (err) => {
        if (next) next(err)
      })
    }

    if (req.method == 'GET') {
      db.get(query, finish)
    }
    else if (req.method == 'POST') {
      receive(req, (err, data) => {
        if (err) return finish(err)
        if (query.attached) {
          let field = Object.keys(query.attached)[0],
              index = data.indexOf(0)
          try {
            let row = index > 0 ? JSON.parse(data.slice(0, index).toString()) : {}
            row[field] = data.slice(index + 1)
            query.rows = [row]
          }
          catch(err) {
            return finish(err)
          }
        }
        else {
          try {
            data = JSON.parse(data.toString())
          }
          catch(err) {
            return finish(err)
          }
          query.rows = Array.isArray(data) ? data : [data]
          if (query.rows.length == 0) {
            return finish(null, [])
          }
        }
        db.update(query, finish)
      })
    }
    else {
      finish(`Unsupported method ${req.method}`)
    }
  })
}

@@ -35,24 +35,57 @@
 re('http'),%0A
+      https  = require('https'),%0A
       URL   
@@ -331,33 +331,25 @@
 %0A%0A  
-return http.createServer(
+function listener
 (req
@@ -354,19 +354,16 @@
 eq, res)
- =%3E
  %7B%0A    l
@@ -1925,12 +1925,156 @@
    %7D%0A  %7D
+%0A%0A  return options.key && options.cert ? https.createServer(options, listener)%0A                                     : http.createServer(listener
 )%0A%7D%0A

Support to run with SSL