add counter implementaiton with async-redis

This commit is contained in:
Jakub Sokołowski 2018-10-16 13:55:00 -04:00
parent a49902da00
commit 186116c6c3
3 changed files with 28 additions and 17 deletions

View File

@ -4,7 +4,7 @@
"description": "Minimal API for counting clicks", "description": "Minimal API for counting clicks",
"main": "index.js", "main": "index.js",
"dependencies": { "dependencies": {
"ioredis": "^4.1.0", "async-redis": "^1.1.4",
"koa": "^2.5.3", "koa": "^2.5.3",
"koa-json": "^2.0.2", "koa-json": "^2.0.2",
"koa-router": "^7.4.0" "koa-router": "^7.4.0"

View File

@ -1,14 +1,20 @@
//const Redis = require('ioredis') class Counter {
//const redis = new Redis() constructor(redis) {
this.redis = redis
/* make sure we don't miss errors */
this.redis.on("error", (err) => { console.log("Error: " + err) })
}
var COUNTER = 0 async incr (val) {
/* default to incrementing by one */
exports.incr = (val) => { val = val == undefined ? 1 : val
/* default to incrementing by one */ /* increment */
val = val == undefined ? 1 : val this.redis.incr('default')
COUNTER += val }
async state () {
return await this.redis.get('default')
}
} }
exports.state = () => { module.exports = Counter
return COUNTER
}

View File

@ -1,22 +1,27 @@
const Koa = require('koa') const Koa = require('koa')
const Router = require('koa-router') const Router = require('koa-router')
const JSON = require('koa-json') const JSON = require('koa-json')
const Counter = require('./counter')
const Counter = require('./counter')
const Redis = require('async-redis')
/* DEFAULTS */ /* DEFAULTS */
let LISTEN_PORT = 3000 const REDIS_HOST = 'localhost'
const REDIS_PORT = 6379
const LISTEN_PORT = 3000
const app = new Koa() const app = new Koa()
const router = new Router() const router = new Router()
const redis = Redis.createClient(REDIS_PORT, REDIS_HOST)
const counter = new Counter(redis)
router.put('/click', async ctx => { router.put('/click', async ctx => {
Counter.incr() counter.incr()
ctx.body = { 'counter': Counter.state() } ctx.body = { 'counter': await counter.state() }
}); });
router.get('/clicks', async ctx => { router.get('/clicks', async ctx => {
ctx.body = { 'counter': Counter.state() } ctx.body = { 'counter': await counter.state() }
}); });
app.use(JSON({pretty: true})) app.use(JSON({pretty: true}))