Hey everyone, I have a query, how can I use top le...
# help
a
Hey everyone, I have a query, how can I use top level await in sst with typescript. I did switch the module system from 
commonjs
 to 
esnext
 and I’m already targeting 
es2018
 . I also did switch my function runtime to use Node 14.x but I still get transpilation error saying that top-level await isn’t supported, any ideas?
This is the error that I see when I use top-level await
Copy code
error: Top-level await is not available in the configured target environment
j
Is this for a Lambda function, can I also see a code snippet of how you are using it?
a
Yep, this is for a lambda function
Copy code
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 { Genre as IGenre } from '../../types/Genre';
import GenreSchema from '../../schema/Genre';
import { connectToDb } from '../../utils/mongo-client';

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<Static<typeof IGenre>>('Genre', GenreSchema);
  const genres = await Genre.find(query, ['title', 'slug', 'imageUrl', 'videoUrl', 'sortOrder'], {
    sort: { sortOrder: 1 },
  });
  return { statusCode: 200, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(genres) };
};

const handler = middy(baseHandler);

handler.use(httpErrorHandler()).use(httpHeaderNormalizer());

module.exports = { handler };
This is what I’m doing right now. I would ideally want to keep the
connection
and
Genre
objects out of the base handler for caching / reusability reasons and to also reduce response times. How should I go about that?
j
I’m not sure about this specific code but you shouldn’t have to do
module.exports
. You can just
export
it directly. Did that work for you?
a
Oh yes, there’s no need for
module.exports
! It’s just an habit that’s hard to get rid of,
export default handler
works without any problems. I’ll check if that solves the top-level await error and let you know.
j
👍