Skip to content

Instantly share code, notes, and snippets.

@alvinslee
Created September 16, 2022 03:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alvinslee/62cb4ad3390740ed8a15e2da11d0d020 to your computer and use it in GitHub Desktop.
Save alvinslee/62cb4ad3390740ed8a15e2da11d0d020 to your computer and use it in GitHub Desktop.
Salesforce Function - Caching Example
export default async function (event, context, logger) {
logger.info(`Invoking Datafunction with payload ${JSON.stringify(event.data || {})}`);
const redis = await redisConnect();
let cached = {};
// Check Redis for cached entry first
let big_biz_count = await redis.get(`big_biz`);
if (big_biz_count) {
// If cached entry found, return it and be done.
logger.info(`Found cache entry = ${big_biz_count}`);
cached = "true"
redis.quit();
return { big_biz_count, cached }
} else {
// If cached entry not found, then:
// 1. Run the Postgres query
// 2. Store the result in Redis
// 3. Return the result and be done
logger.info(`did not find in cache, returned ${big_biz_count}`);
cached = "false"
const pg = await pgConnect();
const { rows } = await pg.query('SELECT COUNT(*) FROM company WHERE employees>10000;');
big_biz_count = rows[0].count.toString();
redis.set(`big_biz`, big_biz_count, {
EX: 30, // seconds to keep before expiring
NX: true
});
// Close the connections
redis.quit();
pg.end();
// Return the value from Postgres, now stored in Redis
return { big_biz_count, cached }
}
}
/* Helper functions */
// Connect to PostgreSQL
async function pgConnect() {
const DATABASE_URL = process.env.DATABASE_URL;
if (!DATABASE_URL) {
throw new Error("DATABASE_URL is not set");
}
const client = new Client({
connectionString: DATABASE_URL,
ssl: {
rejectUnauthorized: false
}
});
await client.connect();
return client;
}
// Connect to Redis
async function redisConnect() {
const REDIS_URL = process.env.REDIS_URL;
if (!REDIS_URL) {
throw new Error("REDIS_URL is not set");
}
const redis = createClient({
url: process.env.REDIS_URL,
socket: {
tls: true,
rejectUnauthorized: false
}
});
await redis.connect();
redis.on('error', err => {
console.log('Error ' + err);
});
return redis;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment