Last active
June 20, 2024 04:55
-
-
Save kevboutin/dfa9974f3a4a33fbff7c85785fc9c37c to your computer and use it in GitHub Desktop.
This is just a sample Azure function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const mongoose = require('mongoose').set('debug', process.env.NODE_ENV !== 'production'); | |
const SampleService = require('./sampleService'); | |
const DatabaseCache = require('./databaseCache'); | |
// The time-to-live in seconds for each cache entry. | |
const cacheTtl = process.env.CACHE_TTL || 3600; | |
// The cache must live in global scope so it remains in memory between invocations. | |
let databaseCache = new DatabaseCache(cacheTtl); | |
const sampleFunctionHandler = async (context, req) => { | |
let databaseService; | |
// Boilerplate section ------------------------------ | |
// First we fetch secrets by parsing the request. This section is intentionally removed to simplify. | |
// The dbHost came from secrets above. | |
const cacheName = `${dbHost}`; | |
// In some functions, the following code may have to get two connections instead of just one. | |
// Check if a cache exists. | |
const cacheExists = databaseCache.cacheExists(cacheName); | |
if (cacheExists) { | |
// We already have the databaseService cached, so this will not create a new one. | |
databaseService = databaseCache.getService(cacheName, {}); | |
} else { | |
// This will create a new cache entry with a new DatabaseService. | |
databaseService = databaseCache.getCache(cacheName, { | |
dbUri, | |
dbName, | |
databaseOpts, | |
}); | |
} | |
// End of Boilerplate section ------------------------------ | |
try { | |
// Use the connection to query the database via a service. | |
const conn = await databaseService.getConnection(context); | |
const sampleService = new SampleService(conn); | |
const result = await sampleService.findById(someIdFromRequest); | |
} catch (error) { | |
// Return an error response. | |
context.res.status = 500; | |
context.res.body = error.message; | |
return context.res; | |
} | |
// Return a response. | |
context.res.status = 200; | |
context.res.body = result; | |
return context.res; | |
}; | |
module.exports = sampleFunctionHandler; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment