Matthew Smithburger
10/17/2021, 10:32 PMFrank
Ashishkumar Pandey
10/17/2021, 11:34 PMimport mongoose from 'mongoose';
const uri = process.env.MONGODB_URI;
if (!uri) {
throw new Error('Error connecting to database');
}
let cachedPromise: Promise<mongoose.Connection> | null = null;
export const connectToDb = async (): Promise<mongoose.Connection> => {
if (!cachedPromise) {
cachedPromise = mongoose.createConnection(uri, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false,
connectTimeoutMS: 5000,
bufferCommands: false,
bufferMaxEntries: 0,
poolSize: 20,
autoIndex: false,
});
}
const connection = await cachedPromise;
return connection;
};
And here’s how the lambda function would use it :-
import type { APIGatewayProxyEvent, Context, APIGatewayProxyResult } from 'aws-lambda';
import middy from '@middy/core';
import httpHeaderNormalizer from '@middy/http-header-normalizer';
import httpErrorHandler from '@middy/http-error-handler';
import { Static } from 'runtypes';
import { IGenre } from '../../types/Genre';
import GenreSchema from '../../schema/Genre';
import { connectToDb } from '../../utils/mongo-client';
type Genre = Static<typeof IGenre>;
const baseHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => {
context.callbackWaitsForEmptyEventLoop = false;
const query = { isActive: true, forLoLoMo: true };
const connection = await connectToDb();
const Genre = connection.model<Genre>('Genre', GenreSchema);
const genres = await Genre.find(query, [], { sort: { sortOrder: 1 } });
return { statusCode: 200, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(genres) };
};
export const handler = middy(baseHandler);
handler.use(httpHeaderNormalizer()).use(httpErrorHandler());
Hope this helps. This used to give me around 350 - 800 ms response times on cached connections. Around 1s to 1.2s on new connections and 1.5 to 1.8s on cold starts.
You could try atlas vpc peering to reduce the connection time or you could use mongodb serverless which is in beta. You can’t use mongoose with mongodb serverless though.Matthew Smithburger
10/18/2021, 6:42 AMWilliam Hatch
02/03/2022, 6:48 PMAshishkumar Pandey
02/03/2022, 6:59 PMWilliam Hatch
02/03/2022, 7:09 PMAshishkumar Pandey
02/03/2022, 8:01 PMWilliam Hatch
02/03/2022, 8:58 PM