Skip to content

Instantly share code, notes, and snippets.

View somesh-m's full-sized avatar
🏠
Working from home

Somesh Mohan somesh-m

🏠
Working from home
View GitHub Profile
const RedisConnectionHelper = require('./redisHelper')
const checkApiRate = (scriptSHA) => {
return async(req, res, next) => {
let redisInstance = await RedisConnectionHelper.getInstance();
try {
let result = await redisInstance.EVALSHA(scriptSHA,{keys:[req.body.userId]})
if(result == 'True') {
//Allow this request
next();
} else {
@somesh-m
somesh-m / app.js
Created November 16, 2023 05:20
Nodejs code for sample rate limiter
const express = require('express');
const RedisConnectionHelper = require('./redisHelper')
const checkApiRate = require('./CheckAPIRate')
const fs = require('fs')
const app = express();
const port = 3000;
async function initializeApp() {
let redisInstance = await RedisConnectionHelper.getInstance();
@somesh-m
somesh-m / CheckCounter.lua
Last active November 16, 2023 05:17
Lua script used for atomically handling api rate counter
local logchannel = "tokenbucketdebug"
-- This function will be used to log debug messages to redis pub/sub channel
local function logit(msg)
redis.pcall("PUBLISH", logchannel, msg)
end
local key = KEYS[1]
local logPrependText = "User: "..key
local availableToken = redis.call('GET', 'tokens_'..key)
if availableToken == false then
@somesh-m
somesh-m / sum.c
Created August 11, 2020 08:18
Sample Redis Module Command Function
/**
SUM <key> <startIndex> <endIndex>
*/
int sumCommand(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
int replyIndex, replyLength;
long long value;
long long sum = 0;
RedisModuleCallReply *tempReply;
RedisModuleString *tempString;
RedisModule_Log(ctx,"debug","Inside Sum Function %d", argc);
@somesh-m
somesh-m / onload.c
Created August 11, 2020 08:16
Redis Module Sample On Load
int RedisModule_OnLoad(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
// init function
if(RedisModule_Init(ctx, "stats", 1, REDISMODULE_APIVER_1) == REDISMODULE_ERR) {
printf("Error while module initialization");
return REDISMODULE_ERR;
}
// Create commands
if(RedisModule_CreateCommand(ctx, "stats.total", sumCommand, "readonly", 0, 0, 0) == REDISMODULE_ERR) {
printf("Error while command initialization");
return REDISMODULE_ERR;