0

I have this middleware that gets the aws lambda function event:

export function hasuraActionHandler<Input, Output>(
  allowedRoles: string[],
  handler: (
    input: Input,
    hasuraRole: string,
    hasuraUserId?: string,
    ipAddress?: string,
    // @ts-ignore
    context: Context,
  ) => Promise<typeof formatJSONResponse<Output>>
) :any {
  return async (event, context, callback) => {
    const { hasuraRole, hasuraUserId, input, ipAddress } =
      getHasuraActionParams<Input>(event);

    if (!allowedRoles.includes(hasuraRole)) {
      return callback(null, {
        statusCode: 403,
        body: JSON.stringify({
          message: 'Forbidden',
        }),
      });
    }

    try {
      callback(null, {
        statusCode: 200,
        body: await handler(input, hasuraRole, hasuraUserId, ipAddress, context),
      });
    } catch (e) {
      console.error(e);

      return callback(null, {
        statusCode: 400,
        body: JSON.stringify({
          message: e
        }),
      });
    }
  };
}

getHasuraActionParams function:

export function getHasuraEventParams<T>(event: APIGatewayEvent): {
  data: T;
  hasuraRole: string;
  hasuraAllowedRoles?: string[];
  hasuraUserId?: string;
} {
  const data = parse(event.body).event.data
  const {
    "x-hasura-allowed-roles": hasuraAllowedRoles,
    "x-hasura-role": hasuraRole,
    "x-hasura-user-id": hasuraUserId
  } = parse(event.body).event.session_variables;
  return { data, hasuraRole, hasuraAllowedRoles, hasuraUserId };
}

the aws function:

const ban_account = hasuraActionHandler<ban_accountArgs, ban_account_output>(
  ["admin"],
  async (input, hasuraRole, hasuraUserId, context) => {
    
    .... 

    return formatJSONResponse({
      id: "1"
    });
  }
);

ban_account_output type:

type ban_account_output = {
  id: string;
};

the formatJSONResponse function:

export const formatJSONResponse = (response: Record<string, unknown>) => {
  return {
    statusCode: 200,
    body: JSON.stringify(response)
  };
};

Question is, how to type the Promise<typeof formatJSONResponse<Output> in the middleware? As is it throws this: TS2635: Type '(response: Record ) => { statusCode: number; body: string; }' has no signatures for which the type argument list is applicable.

Is it also possible to type the :any on the middleware?

codesandbox: https://codesandbox.io/s/lingering-pond-wcu8go?file=/src/index.ts

Stathis Ntonas
  • 1,222
  • 2
  • 20
  • 49

0 Answers0