From 186116c6c35c0fa6565b5165b3ad1f22b3ebc77e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Soko=C5=82owski?= Date: Tue, 16 Oct 2018 13:55:00 -0400 Subject: [PATCH] add counter implementaiton with async-redis --- package.json | 2 +- src/counter.js | 28 +++++++++++++++++----------- src/index.js | 15 ++++++++++----- 3 files changed, 28 insertions(+), 17 deletions(-) diff --git a/package.json b/package.json index de969c8..0254fc4 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "description": "Minimal API for counting clicks", "main": "index.js", "dependencies": { - "ioredis": "^4.1.0", + "async-redis": "^1.1.4", "koa": "^2.5.3", "koa-json": "^2.0.2", "koa-router": "^7.4.0" diff --git a/src/counter.js b/src/counter.js index 35d9561..436dc83 100644 --- a/src/counter.js +++ b/src/counter.js @@ -1,14 +1,20 @@ -//const Redis = require('ioredis') -//const redis = new Redis() +class Counter { + constructor(redis) { + this.redis = redis + /* make sure we don't miss errors */ + this.redis.on("error", (err) => { console.log("Error: " + err) }) + } -var COUNTER = 0 - -exports.incr = (val) => { - /* default to incrementing by one */ - val = val == undefined ? 1 : val - COUNTER += val + async incr (val) { + /* default to incrementing by one */ + val = val == undefined ? 1 : val + /* increment */ + this.redis.incr('default') + } + + async state () { + return await this.redis.get('default') + } } -exports.state = () => { - return COUNTER -} +module.exports = Counter diff --git a/src/index.js b/src/index.js index 794e118..65503b1 100644 --- a/src/index.js +++ b/src/index.js @@ -1,22 +1,27 @@ const Koa = require('koa') const Router = require('koa-router') const JSON = require('koa-json') -const Counter = require('./counter') +const Counter = require('./counter') +const Redis = require('async-redis') /* DEFAULTS */ -let LISTEN_PORT = 3000 +const REDIS_HOST = 'localhost' +const REDIS_PORT = 6379 +const LISTEN_PORT = 3000 const app = new Koa() const router = new Router() +const redis = Redis.createClient(REDIS_PORT, REDIS_HOST) +const counter = new Counter(redis) router.put('/click', async ctx => { - Counter.incr() - ctx.body = { 'counter': Counter.state() } + counter.incr() + ctx.body = { 'counter': await counter.state() } }); router.get('/clicks', async ctx => { - ctx.body = { 'counter': Counter.state() } + ctx.body = { 'counter': await counter.state() } }); app.use(JSON({pretty: true}))