Is there a way to streamline or simplify these typescript functions?

I am working with two functions:

import { handler } from '../lib/handler-lib'
import { APIGatewayEvent, Context } from 'aws-lambda'

export const producer = handler(async (
  _event: APIGatewayEvent,
  _context: Context
): Promise<object> => {
  return {
    some: 'data result'
  }
})
import {
  APIGatewayEvent,
  APIGatewayProxyResult,
  Context
} from 'aws-lambda'

export const handler = (lambda: Function): object => {
  return async (
    event: APIGatewayEvent,
    context: Context
  ): Promise<APIGatewayProxyResult> => {
    let body: object
    let statusCode: number

    try {
      body = await lambda(event, context)
      statusCode = 200
    } catch (e) {
      body = { error: e.message }
      statusCode = 500
    }

    return {
      body: JSON.stringify(body),
      statusCode
    }
  }
}

Is there a way to simplify these functions?

Both functions currently define types for event and context. If only the second function does this, all callers could benefit from type declarations automatically.

Should the arguments of lambda: Function be explicitly defined?

Answer №1

Firstly, it's important to provide a clear definition for the lambda function, specifying its input and output values.

lambda: (e: APIGatewayEvent, ctx: Context) => Promise<any>

You can also enhance your code by simplifying it and eliminating temporary variables:

import {
  APIGatewayEvent,
  APIGatewayProxyResult,
  Context
} from 'aws-lambda'

export const handler = (lambda: (e: APIGatewayEvent, ctx: Context) => Promise<any;): object => {
  return async (
    event: APIGatewayEvent,
    context: Context
  ): Promise<APIGatewayProxyResult> => {
    try {
      return {
          body: JSON.stringify(await lambda(event, context)),
          statusCode: 200
      } 
    } catch (e) {
         return {
          body: JSON.stringify({ error: e.message }),
          statusCode: 500
      } 
    }
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fastify Typescript: dealing with an unidentified body

I'm new to Fastify and I've encountered a problem with accessing values in the body using Typescript. Does anyone have any ideas or suggestions? Thanks! Update: I want to simplify my code and avoid using app.get(...) Here's my code snippet ...

Automate the process of triggering the "Organize Imports" command on a VSCode / Typescript project through code

Is there a way to automatically run VSCode's 'Organize Imports' quickfix on every file in a project, similar to how tslint can be run programatically over the entire project? tslint --project tsconfig.json --config tslint.json --fix I want ...

Encountering an issue when attempting to upgrade to Angular 9: Error arising in metadata creation for exported symbol

I am currently in the process of upgrading my Angular 8 application to Angular 9. When running the migration command, I encountered the following issue: Undecorated classes with DI migration. As of Angular 9, it is no longer supported to use Angular ...

Typescript's Nested Type Assignments

Simply put, I'm making an API call and receiving the following data: { getUserInfo: { country: 'DE', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3c48594f487c59445d514c5059125f5351">[e ...

Trouble arises when trying to open a new window using the Angular 8 CDK

I am attempting to open my component in a new window, similar to this example: https://stackblitz.com/edit/angular-open-window However, when the window opens, my component is not displayed and I receive the following error in the console: Error: Must pro ...

Create a recursive array structure that contains two distinct data types and specific guidelines

I have a unique array structure where the odd index always contains elements of TypeA and the even index always contains elements of TypeB. It is guaranteed that this array will always have an even length, never odd. The data structure of this array must ...

The property 'i' is not recognized on the type 'AppComponent'

Check out my code here; Take a look at my code here I attempted to implement a delete button to remove array objects using the ngFor directive ...

The payload from the Axios POST request is failing to reach its destination endpoint

I have two Express servers up and running - a gateway and an authentication service. I am facing an issue where the payload I set in the body of a request from my gateway to the authentication server never seems to arrive, despite there being no apparent C ...

Differences between Typescript compilation: Using dot notation vs square brackets when accessing non-existent properties

Imagine having the given class and code snippet: class myClass{ x: number; } const obj = new myClass(); obj.y = 7; // produces a compile error. Property 'y' does not exist on type myClass. obj['y'] = 7; // compiles without any issu ...

The type '{ children: Element; }' is lacking the specified properties within type - NextJS version 13.0.6 with TypeScript version 4.9.3

Currently, I am delving into NextJS / TypeScript and have come across a type error. The component structure is as follows: interface LayoutProps { children: React.ReactNode; title: string; keywords: string; description: string; } const Lay ...

Customizing the Position of Material UI Select in a Theme Override

I'm trying to customize the position of the dropdown menu for select fields in my theme without having to implement it individually on each select element. Here's what I've attempted: createMuiTheme({ overrides: { MuiSelect: { ...

Can you inherit a type based on the keyof template in TypeScript?

I attempted a small hack to explore how DOM ts files map different element names to their types. My experiment involved trying to have a type MyType extend a different set of fields depending on the value of a string. Here is what I tried: interface Messa ...

Saving Data in an Angular Material Table: A How-to Guide

I have a basic angular material table and I am looking for a way to save the data displayed in each row when a button is clicked. Is it possible to save each row of data as an object and push it to an array? If so, how can I achieve this? <div class=& ...

Discovering the object and its parent within a series of nested arrays

Is there a way to locate an object and its parent object within a nested array of unknown size using either lodash or native JavaScript? The structure of the array could resemble something like this: name: 'Submodule122'</p> I have been ...

Why do we often encounter a "SyntaxError: Unexpected token ;" error when a seemingly normal semicolon is present in distribution files?

Currently, I am in the process of developing a newsletter subscription API using node.js and typescript. This project involves my first experience with typeorm and PostgreSQL. Following several tutorials, I configured typeorm and created the entity types a ...

Could someone teach me how to implement icon rotation in Vue.js using Vuetify?

I am currently working on adding a feature where the icon rotates when the button is clicked, moving from down to up and vice versa in a spinning motion. Here is the code I have so far: <template> <v-btn v-on:click="isShow = !isShow" ...

Discover new films with TheMovieDB - Explore a random movie

Currently, I am utilizing the movie database API () to search for movies based on criteria such as popularity, name, or ID. However, I am now interested in incorporating a random movie generator feature on my website despite there being no clear instructio ...

How can the file system module (fs) be utilized in Angular 7?

Hello, I am currently working with Angular 7. I recently attempted to utilize the fs module in Typescript to open a directory. However, I encountered an error message stating: "Module not found: Error: Can't resolve fs". Despite having types@node and ...

What is the best way to retrieve the Base64 string from a FileReader in NextJs using typescript?

My goal is to extract a string from an object I am receiving in the response. const convertFileToBase64 = (file: File): Promise<string> => { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.r ...

Making Amazon Cognito function seamlessly with angular2 and typescript

Having trouble getting Cognito’s Forgot password feature to work Using: Angular2+Typescript+Ionic New to this process, followed a Quickstart guide I found here No matter what I try, keep getting errors like Cannot read property 'CognitoUser' ...