Switch from local store to redis

This commit is contained in:
Peter Morton 2023-10-11 19:17:13 -05:00
parent 58f176b344
commit ae9f0fae73
6 changed files with 71 additions and 49 deletions

View File

@ -1,14 +1,16 @@
import localStorage from "local-storage";
import { store } from "../../utils/index.js";
import createHttpError from "http-errors";
export default (req, res, next) => {
if (localStorage(req.query.authKey) == null) {
next(
new createHttpError.Forbidden(
`middleware:authKey ${req.query.authKey} not authenticated`
)
);
return;
}
store.get(req.query.authKey).then((value) => {
if (value == null) {
next(
new createHttpError.Forbidden(
`middleware:authKey ${req.query.authKey} not authenticated`
)
);
return;
}
});
next();
};

View File

@ -1,10 +1,9 @@
import { Router } from "express";
import axios from "axios";
import { logger } from "../../utils/index.js";
import { logger, store } from "../../utils/index.js";
import { decode } from "jsonwebtoken";
import jwt from "jsonwebtoken";
import jwkToPem from "jwk-to-pem";
import localStorage from "local-storage";
const router = Router();
@ -73,23 +72,26 @@ router.all("/", (req, res, next) => {
tenant: issSplit[1],
};
const authDataString = JSON.stringify(authData);
logger.info(
`Adding ${
verified.sub
} to local-stoage for environment ${JSON.stringify(authData)}`
`Adding agent ${verified.sub} to store for environment ${authDataString}}`
);
localStorage(verified.sub, authData);
if (sessionIdentifier && sessionIdentifier.length > 0) {
logger.info(
`Adding ${sessionIdentifier} to local-stoage for environment ${JSON.stringify(
authData
)}`
);
localStorage(sessionIdentifier, authData);
}
res.send(decoded);
store
.hSet(verified.sub, authData)
.then(() => {
if (sessionIdentifier && sessionIdentifier.length > 0) {
logger.info(
`Adding sessionIdentifier ${sessionIdentifier} to store for environment ${authDataString}`
);
return store.hSet(sessionIdentifier, authData);
}
})
.then(() => {
res.send(decoded);
}).catch((e) => {
logger.error(e); // "Uh-oh!"
});;
} catch (err) {
logger.error(`Verify failed [${JSON.stringify(err, null, 2)}].`);
next(err);

View File

@ -1,12 +1,10 @@
import { Router } from "express";
import axios from "axios";
import localStorage from "local-storage";
import sampleFlow from "../../utils/sampleFlow.js";
const router = Router();
import { logger } from "../../utils/index.js";
import { logger, store } from "../../utils/index.js";
import { referenceIdQuery } from "../../utils/graphQueries.js";
router.get("/", (req, res) => {
router.get("/", async (req, res) => {
const data = {
nodes: [],
links: [],
@ -35,8 +33,8 @@ router.get("/", (req, res) => {
// FIX for 'endTime' parameter cannot be later than one minute prior to now.
endTime.setMinutes(endTime.getMinutes() - 1);
const { host, tenant, token } = localStorage(req.query.authKey);
const auth = await store.hGetAll(req.query.authKey);
const { host, tenant, token } = auth;
axios
.post(
`${host}/unified-data-gateway/${tenant}/graphql`,
@ -136,13 +134,9 @@ router.get("/", (req, res) => {
logger.debug(`Sending data: ${JSON.stringify(data, null, 2)}`);
res.send(data);
}).catch((e) => {
logger.error(e); // "Uh-oh!"
});
if (req.query.useSampleData) {
const data = sampleFlow(filter);
res.send(data);
return;
}
});
function addLink(data, source, target, _fraction) {

View File

@ -3,24 +3,20 @@ import dotenv from "dotenv";
// Set the NODE_ENV to 'development' by default
process.env.NODE_ENV = process.env.NODE_ENV || "development";
const envFound = dotenv.config();
if (envFound.error) {
// This error should crash whole process
if (process.env.NODE_ENV !== "production") {
const envFound = dotenv.config({ debug: true });
if (envFound.error) {
// This error should crash whole process
throw new Error("⚠️ Couldn't find .env file ⚠️");
throw new Error("⚠️ Couldn't find .env file ⚠️");
}
}
export default {
/**
* Your favorite port
*/
port: parseInt(process.env.PORT, 10),
/**
* Your secret sauce
*/
jwtSecret: process.env.JWT_SECRET,
jwtAlgorithm: process.env.JWT_ALGO,
port: parseInt(process.env.PORT || 3000, 10),
/**
* Used by winston logger
@ -29,6 +25,10 @@ export default {
level: process.env.LOG_LEVEL || "silly",
},
redis: {
url: process.env.REDIS_URL || "redis://localhost:6379",
},
/**
* API configs
*/

View File

@ -1 +1,11 @@
export { default as logger } from "./logger.js";
export { default as store } from "./store.js";
export function isEmpty(obj) {
for (const prop in obj) {
if (Object.hasOwn(obj, prop)) {
return false;
}
}
return true;
}

14
src/utils/store.js Normal file
View File

@ -0,0 +1,14 @@
import { createClient } from 'redis';
import config from "../config/index.js";
import { logger } from "./index.js";
const client = createClient({
url: config.redis.url
});
client.on('error', err => logger.error('Redis Client Error', err));
await client.connect();
logger.info(`Connect store to ${config.redis.url}`)
export default client;