Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict'
- var http = require('http')
- var url = require('url')
- var config = require('./config')
- class TinyCacheServer {
- constructor(host, port){
- this.host = host
- this.port = port
- this.projects = {}
- this.server = http.createServer((req, res) => {
- this._handleRequest(req, res)
- })
- this.server.listen(this.port, this.host)
- }
- _handleRequest(req, res){
- var path = url.parse(req.url).path
- var project = path.split('/')[1]
- var method = path.split('/')[2]
- var key = path.split('/')[3]
- switch (method){
- case 'get':
- this._get(req, res, project, key)
- return
- case 'set':
- this._set(req, res, project, key)
- return
- case 'remove':
- this._remove(req, res, project, key)
- return
- default:
- res.end()
- }
- }
- _get(req, res, project, key){
- if(!project || !key || !this.projects[project] || !this.projects[project][key]) {
- res.end()
- return
- }
- res.end(JSON.stringify(this.projects[project][key]))
- }
- _set(req, res, project, key){
- var chunks = []
- req.on('data', (chunk) => {
- chunks.push(chunk)
- })
- .on('end', () => {
- var body = Buffer.concat(chunks).toString('utf-8').split('=')
- if(body[0] !== 'value' || !key || !project){
- res.end()
- return
- }
- var data = JSON.parse(decodeURIComponent(body[1]))
- if(!this.projects[project]){
- this.projects[project] = {}
- }
- this.projects[project][key] = data
- res.end()
- })
- }
- _remove(req, res, project, key){
- res.end()
- if(!project || !key || !this.data[key]) {
- return
- }
- if(this.projects[project]){
- delete this.projects[project][key]
- }
- }
- }
- new TinyCacheServer(config.host, config.port)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement