aws-lambda#APIGatewayProxyResult TypeScript Examples

The following examples show how to use aws-lambda#APIGatewayProxyResult. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: iframely_post.ts    From roamjs-com with MIT License 6 votes vote down vote up
handler = async (
  event: APIGatewayEvent
): Promise<APIGatewayProxyResult> => {
  const { url, iframe = 'card-small' } = JSON.parse(event.body);
  return axios
    .get(
      `http://iframe.ly/api/oembed?url=${url}&api_key=${process.env.IFRAMELY_API_KEY}&iframe=${iframe}`
    )
    .then((r) => ({
      statusCode: 200,
      body: JSON.stringify(r.data),
      headers: headers(event),
    }))
    .catch((e: Error & AxiosError) => ({
      statusCode: e.response?.status || 500,
      body: e.response?.data ? JSON.stringify(e.response.data) : e.message,
      headers: headers(event),
    }));
}
Example #2
Source File: user-controller.ts    From ddd-cqrs-es-aws-sam with MIT License 6 votes vote down vote up
removeRoleHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => {
  initApplication();

  try {
    _applicationContainer.logger.debug('Remove Role Handler Event: %o', event);

    const userRemoveRoleDto = Object.assign(new UserRemoveRoleDto(), event.pathParameters) as UserRemoveRoleDto;

    await validateOrReject(userRemoveRoleDto);
    await _applicationContainer.get<RemoveUserRoleHandler>(RemoveUserRoleHandler).handle(new RemoveUserRole(userRemoveRoleDto.id, userRemoveRoleDto.roleId));

    return { statusCode: HttpStatus.ACCEPTED, body: null };
  } catch (error) {
    return ApplicationController.handleError(_applicationContainer, error);
  }
}
Example #3
Source File: refund.ts    From sleekypay with MIT License 6 votes vote down vote up
exports.handler = async function (event: APIGatewayEvent): Promise<APIGatewayProxyResult> {

  if (event.httpMethod !== 'POST') {
    return {
      statusCode: 405,
      body: ''
    }
  }

  return getResultPayload(
    event,
    {
      refundId: uuid()
    });
}
Example #4
Source File: iframely_post.ts    From roamjs-com with MIT License 6 votes vote down vote up
handler = async (
  event: APIGatewayEvent
): Promise<APIGatewayProxyResult> => {
  const { url, iframe = 'card-small' } = JSON.parse(event.body);
  return axios
    .get(
      `http://iframe.ly/api/oembed?url=${url}&api_key=${process.env.IFRAMELY_API_KEY}&iframe=${iframe}`
    )
    .then((r) => ({
      statusCode: 200,
      body: JSON.stringify(r.data),
      headers,
    }))
    .catch((e: Error & AxiosError) => ({
      statusCode: e.response?.status || 500,
      body: e.response?.data ? JSON.stringify(e.response.data) : e.message,
      headers,
    }));
}
Example #5
Source File: handler.ts    From antibody-web with MIT License 6 votes vote down vote up
baseHandler = async (event: APIGatewayEvent) : Promise<APIGatewayProxyResult> => {

  const UPLOAD_BUCKET: string = process.env.UPLOAD_BUCKET as string;
  const response = await getNextResult();
  // Return empty success if no images in queue
  if (!response) {
    return {
      statusCode: 204,
      body: "",
      headers: config.defaultHeaders
    };
  }
  let { nextResultId, receiptHandle } = response as NextResultResponse;

  const { downloadUrl } = await getUrls(UPLOAD_BUCKET, nextResultId, { download: true, upload: false });

  return {
    statusCode: 200,
    body: JSON.stringify({
      url: downloadUrl,
      guid: nextResultId,
      receiptHandle
    }),
    headers: config.defaultHeaders
  };
}
Example #6
Source File: auth_get.ts    From roamjs-com with MIT License 6 votes vote down vote up
handler = async (
  event: APIGatewayProxyEvent
): Promise<APIGatewayProxyResult> => {
  const S = event.queryStringParameters?.state || '';
  const key = {
    TableName: "RoamJSAuth",
    Key: { id: { S } },
  };
  return dynamo
    .getItem(key)
    .promise()
    .then((r) => {
      if (r.Item) {
        if (isAfter(new Date(), addMinutes(new Date(r.Item.date.S), 10))) {
          return dynamo
            .deleteItem(key)
            .promise()
            .then(() => bareSuccessResponse(event));
        } else {
          return {
            statusCode: 200,
            body: JSON.stringify({ success: false }),
            headers: headers(event),
          };
        }
      } else {
        return bareSuccessResponse(event);
      }
    })
    .catch((e) => ({
      statusCode: 500,
      body: e.message,
      headers: headers(event),
    }));
}
Example #7
Source File: user-controller.ts    From ddd-cqrs-es-aws-sam with MIT License 6 votes vote down vote up
disableHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => {
  initApplication();

  try {
    _applicationContainer.logger.debug('User Disable Handler Event: %o', event);

    const userDisableDto = Object.assign(new UserDisableDto(), event.pathParameters) as UserDisableDto;

    await validateOrReject(userDisableDto);
    await _applicationContainer.get<DisableUserHandler>(DisableUserHandler).handle(new DisableUser(userDisableDto.id));

    return { statusCode: HttpStatus.ACCEPTED, body: null };
  } catch (error) {
    return ApplicationController.handleError(_applicationContainer, error);
  }
}
Example #8
Source File: get-all-items.ts    From aws-sam-typescript-layers-example with MIT License 6 votes vote down vote up
getAllItemsHandler = async (
    event: APIGatewayProxyEvent,
): Promise<APIGatewayProxyResult> => {
    if (event.httpMethod !== 'GET') {
        throw new Error(`getAllItems only accept GET method, you tried: ${event.httpMethod}`);
    }
    // All log statements are written to CloudWatch
    console.info('received:', event);

    const client = new CustomDynamoClient();
    const items = await client.readAll();

    const response = {
        statusCode: 200,
        body: JSON.stringify(items)
    };

    // All log statements are written to CloudWatch
    console.info(`response from: ${event.path} statusCode: ${response.statusCode} body: ${response.body}`);
    return response;
}
Example #9
Source File: example.ts    From cookiecutter-aws-sam-typescript-layers with MIT License 6 votes vote down vote up
exampleHandler = async (
  event: APIGatewayProxyEvent,
): Promise<APIGatewayProxyResult> => {
  // All log statements are written to CloudWatch
  console.debug('Received event:', event);

  return {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Hello world!',
    })
  };
}
Example #10
Source File: helpers.ts    From crossfeed with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
makeResponse = (
  event: APIGatewayProxyEvent,
  opts: Partial<APIGatewayProxyResult>
): APIGatewayProxyResult => {
  const origin = event.headers?.origin || '*';
  const { body, statusCode = 200, ...rest } = opts;
  return {
    statusCode,
    headers: {
      'Access-Control-Allow-Origin': origin
    },
    body: body ?? '',
    ...rest
  };
}
Example #11
Source File: helpers.ts    From sleekypay with MIT License 6 votes vote down vote up
export function getResultPayload(
  event: APIGatewayEvent,
  fallbackBody: {}): APIGatewayProxyResult {
  const statusCodeString = event.queryStringParameters['statusCode'];

  if (statusCodeString) {
    const statusCode = parseInt(statusCodeString, 10)
    if (statusCode > 299) {
      return {
        statusCode,
        body: ''
      }
    }
  }

  return {
    statusCode: 200,
    body: JSON.stringify(fallbackBody)
  }
}
Example #12
Source File: role-controller.ts    From ddd-cqrs-es-aws-sam with MIT License 6 votes vote down vote up
listHandler = async (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> => {
  initApplication();

  try {
    _applicationContainer.logger.debug('Role List Handler Event: %o', event);

    const roleListDto = Object.assign(new RoleListDto(), event.queryStringParameters) as RoleListDto;
    await validateOrReject(plainToClass(RoleListDto, roleListDto));

    const repository = _applicationContainer.get<ProjectionRepository<RoleProjection>>(DynamoProjectionRepository);
    const roleProjections = await repository.list(process.env.projectionRolesTable, roleListDto);

    return { statusCode: HttpStatus.OK, body: JSON.stringify(roleProjections) };
  } catch (error) {
    return ApplicationController.handleError(_applicationContainer, error);
  }
}
Example #13
Source File: lambda-helpers.ts    From roamjs-com with MIT License 5 votes vote down vote up
bareSuccessResponse = (
  event: Pick<APIGatewayProxyEvent, "headers">
): APIGatewayProxyResult => ({
  statusCode: 200,
  body: JSON.stringify({ success: true }),
  headers: headers(event),
})
Example #14
Source File: defaultResponses.ts    From serverless-SAM-typescript-boilerplate with Apache License 2.0 5 votes vote down vote up
response = {
  success: (statusCode: number = 200, headers: any = {}, data: any = {}): APIGatewayProxyResult => {
    /** Generate default response with no data */
    const response: {
      statusCode: number;
      headers: any;
      body: any;
    } = {
      statusCode,
      headers: {
        'Content-Type': 'application/json',
        ...headers,
      },
      body: JSON.stringify({}),
    };

    /** Add body if status is not 204 and there is data to add.  */
    if (statusCode !== 204)
      response.body = JSON.stringify({
        error: {},
        data,
      });

    return response;
  },
  error: (statusCode: number = 500, headers: any = {}, err?: Error): APIGatewayProxyResult => {
    /** Log the error */
    console.log(err);

    /** Generate default response with no error */
    const response: {
      statusCode: number;
      headers: any;
      body: any;
    } = {
      statusCode,
      headers: {
        'Content-Type': 'application/json',
        ...headers,
      },
      body: JSON.stringify({
        error: {},
        data: {},
      }),
    };

    /** If status code is 500, return a general internal server error */
    if (statusCode === 500) {
      response.body = JSON.stringify({
        error: {
          message:
            'There was an internal server error. Please try again later. If the problem persists, please contact technical support.',
        },
        data: {},
      });
    }

    /** If status code is not 500 and there is an error message, return it */
    if (statusCode !== 500 && err.message) {
      response.body = JSON.stringify({
        error: {
          message: err.message,
        },
        data: {},
      });
    }

    return response;
  },
}
Example #15
Source File: lambda-helpers.ts    From roamjs-com with MIT License 5 votes vote down vote up
serverError = (
  body: string,
  event: Pick<APIGatewayProxyEvent, "headers">
): APIGatewayProxyResult => ({
  statusCode: 500,
  body,
  headers: headers(event),
})
Example #16
Source File: handler.ts    From antibody-web with MIT License 5 votes vote down vote up
baseHandler = async (event: APIGatewayEvent) : Promise<APIGatewayProxyResult> => {

  const body: ReviewResultRequest = JSON.parse(event.body!);
  const guid = event.pathParameters?.guid;
  const DYNAMO_TABLE: string = process.env.DYNAMO_TABLE as string;
  const REVIEW_QUEUE_NAME: string = process.env.REVIEW_QUEUE_NAME as string;

  if (!body || !guid) {
    return {
      statusCode: 400,
      body: JSON.stringify({
        error: "Missing request fields"
      }),
      headers: config.defaultHeaders
    };
  }

  const { value: { reviewedResult, receiptHandle }, error } = validateReviewRequest(body);

  if (error) {
    logger.error("Request failed validation", body, error);
    return {
      statusCode: 400,
      body: JSON.stringify({
        error: error.details?.[0]?.message || "Invalid request body" 
      }),
      headers: config.defaultHeaders
    };
  }

  let record = await getTestRecord(DYNAMO_TABLE, guid);

  if (!record) {
    return {
      statusCode: 404,
      body: JSON.stringify({
        error: `No record found with id ${guid}`
      }),
      headers: config.defaultHeaders
    };
  } else {
    record.review = {
      originalResult: record?.result!,
      status: "reviewed",
      reviewedResult: reviewedResult,
      reviewedAt: Date.now(),
      reviewerId: event.requestContext.identity.cognitoIdentityId!
    };
  }

  await putTestRecord(DYNAMO_TABLE, record);
  await deleteMessage(REVIEW_QUEUE_NAME, receiptHandle);

  return {
    statusCode: 200,
    body: JSON.stringify(record),
    headers: config.defaultHeaders
  };
}
Example #17
Source File: lambda-helpers.ts    From roamjs-com with MIT License 5 votes vote down vote up
userError = (
  body: string,
  event: APIGatewayProxyEvent
): APIGatewayProxyResult => ({
  statusCode: 400,
  body,
  headers: headers(event),
})
Example #18
Source File: index.ts    From exevo-pan with The Unlicense 5 votes vote down vote up
filterCurrentAuctions = async (
  event: APIGatewayProxyEvent,
): Promise<APIGatewayProxyResult> => {
  if (!event.body) {
    return {
      statusCode: 400,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Headers': '*',
        'Access-Control-Allow-Credentials': true,
      },
      body: JSON.stringify({ error: 'empty body' }),
    }
  }

  const currentAuctions = filterOldAuctions(auctions)

  const serializedBody: SerializedFilterBody = JSON.parse(event.body as string)
  const { filterOptions, sortOptions, paginationOptions } =
    deserializeBody(serializedBody)

  const filteredAuctions = filterCharacters({
    auctions: currentAuctions,
    filters: filterOptions,
  })

  const sortedAuctions = applySort(filteredAuctions, sortOptions)

  const paginatedData = paginateData(sortedAuctions, paginationOptions)

  const responseBody = {
    ...paginatedData,
    ...sortOptions,
  }

  return {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Headers': '*',
      'Access-Control-Allow-Credentials': true,
    },
    body: JSON.stringify(responseBody),
  }
}
Example #19
Source File: lambda-helpers.ts    From roamjs-com with MIT License 5 votes vote down vote up
emailCatch =
  (subject: string, event: APIGatewayProxyEvent) =>
  (e: Error): Promise<APIGatewayProxyResult> =>
    emailError(subject, e).then((id) => ({
      statusCode: 500,
      body: `Unknown error - Message Id ${id}`,
      headers: headers(event),
    }))
Example #20
Source File: handler.ts    From hasura-cdk with MIT License 5 votes vote down vote up
export async function handler(event: APIGatewayEvent, context: unknown): Promise<APIGatewayProxyResult> {
    try {

        console.log(event);

        let fortuneCount = 1;

        if (event.body) {

            const body = JSON.parse(event.body) as {
                session_variables: {
                    'x-hasura-role': string;
                };
                input: {
                    arg1: {
                        count: number;
                    };
                    action: {
                        name: string;
                    };
                };
            };
            fortuneCount = body.input.arg1.count;

        }

        const fortunes: string[] = [];

        for (let i = 0; i < fortuneCount; i++) {
            fortunes.push(fortune());
        }

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

    } catch (err) {
        console.error(err);
        return { statusCode: 500, body: 'Something went wrong' };
    }

}
Example #21
Source File: handler.ts    From antibody-web with MIT License 5 votes vote down vote up
baseHandler = async (event: NotifyEvent): Promise<APIGatewayProxyResult> => {

  const secretsmanager = new AWS.SecretsManager();
  const secret  = await secretsmanager.getSecretValue({ SecretId: "push-notification-vapid-private" })
    .promise()
    .then(({ SecretString }) => SecretString) as string;
  
  const privateKeySecret : PrivateKeySecret = JSON.parse(secret);
  const publicKey = "BD9NGDhi_Ff3-VoFXB2KuXMd_fn_X4iAGzYs3d_joyU57zV-OAY8oAo7Fl577F2rv3hi3d9GJ5UB-oqzRn7umdk";
  
  const pushSubscription = event.subscription;

  const payload = JSON.stringify({
    title: 'Your Antibody Test Timer has Finished',
    body: "Please click here to continue with your test",
    actions: [
      {
        action: 'return-to-test',
        title: 'Continue'
      }
    ]
  });

  // @TODO: get proper mailto address 
  const options = {
    vapidDetails: {
      subject: 'mailto:[email protected]',
      publicKey,
      privateKey: privateKeySecret.privateKey
    }
  };

  await webpush.sendNotification(
    pushSubscription,
    payload,
    options  
  );

  return {
    statusCode: 200,
    body: JSON.stringify({ message: "NOTIFYING!" }),
    headers: config.defaultHeaders
  };
}
Example #22
Source File: helpers.ts    From crossfeed with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
NotFound: APIGatewayProxyResult = {
  statusCode: 404,
  body: ''
}
Example #23
Source File: slack-url_post.ts    From roamjs-com with MIT License 5 votes vote down vote up
handler = async (
  event: APIGatewayEvent
): Promise<APIGatewayProxyResult> => {
  const { code } = JSON.parse(event.body);
  return axios
    .post<{
      access_token: string;
      authed_user: { access_token: string; id: string };
      team: { name: string };
      ok: boolean;
      error: string;
    }>(
      "https://slack.com/api/oauth.v2.access",
      querystring.stringify({
        code,
        client_id: process.env.SLACK_CLIENT_ID,
        client_secret: process.env.SLACK_CLIENT_SECRET,
        redirect_uri: "https://roamjs.com/oauth?auth=true",
      }),
      {
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
      }
    )
    .then((r) =>
      r.data.ok
        ? web.users
            .info({ token: r.data.access_token, user: r.data.authed_user.id })
            .then((u) =>
              u.ok
                ? {
                    statusCode: 200,
                    body: JSON.stringify({
                      token: r.data.access_token,
                      user_token: r.data.authed_user.access_token,
                      label: `${(u.user as { name: string }).name} (${
                        r.data.team.name
                      })`,
                    }),
                    headers: headers(event),
                  }
                : {
                    statusCode: 500,
                    body: r.data.error,
                    headers: headers(event),
                  }
            )
        : {
            statusCode: 500,
            body: r.data.error,
            headers: headers(event),
          }
    )
    .catch((e) => ({
      statusCode: e.response?.status || 500,
      body: e.response?.data ? JSON.stringify(e.response.data) : e.message,
      headers: headers(event),
    }));
}
Example #24
Source File: handler.ts    From antibody-web with MIT License 4 votes vote down vote up
baseHandler = async (event: APIGatewayEvent): Promise<APIGatewayProxyResult> => {

  const guid = event.requestContext.authorizer?.principalId;

  logger.info("Updating test record for user with guid:", guid);

  if (!guid) {
    logger.error("No guid available in request context");
    return {
      statusCode: 400,
      body: JSON.stringify({
        error: "Missing user id"
      }),
      headers: config.defaultHeaders
    };
  }

  const parsedBody: UpdateTestRequest = JSON.parse(event.body as string);

  if (!parsedBody) {
    logger.error("Could not parse update body", event.body);
    return {
      statusCode: 400,
      body: JSON.stringify({
        error: "Missing event body"
      }),
      headers: config.defaultHeaders
    };
  }
  
  const { error: envError } = validateUpdateEnvironment(process.env);
  
  if (envError) {
    logger.error("Environment not configured correctly", envError);
    return {
      statusCode: 400,
      body: JSON.stringify({
        error: "Environment configuration error"
      }),
      headers: config.defaultHeaders
    };
  }

  const DYNAMO_TABLE: string = process.env.DYNAMO_TABLE as string;

  //Pull out our variables from the event body, once validated

  const { value: request, error: uploadError } = validateUpdateRequest(parsedBody);
  
  if (uploadError) {
    logger.error("Request failed validation", parsedBody, uploadError);
    return {
      statusCode: 400,
      body: JSON.stringify({
        error: uploadError.details?.[0]?.message || "Invalid request body" 
      }),
      headers: config.defaultHeaders
    };
  }

  const { testRecord }: {testRecord: TestRecord } = request;

  logger.info("Updating record...");
  // Make sure we're always saving to the user's actual id, in case anyone tries to spoof the guid in their request.
  if (testRecord.guid !== guid) {
    logger.error("WARNING: Attempted to save record to another user's guid");
    throw new Error("Attempted to save with user_id that does not belong to this user");
  }

  const oldRecord = await getTestRecord(DYNAMO_TABLE, guid);

  // Only schedule our notification if we are receiving the user's subscription for the first time
  if (!oldRecord?.notificationSubscription && testRecord.notificationSubscription) {
    scheduleNotification({
      subscription: testRecord.notificationSubscription
    }, {
      wait: 10
    });
  }
  
  await putTestRecord(DYNAMO_TABLE, testRecord);
  
  //Response
  logger.debug(testRecord);
  logger.info("Updating record complete");

  return {
    statusCode: 200,
    body: JSON.stringify({ testRecord }),
    headers: config.defaultHeaders
  };
}
Example #25
Source File: customer_post.ts    From roamjs-com with MIT License 4 votes vote down vote up
handler = async (
  event: APIGatewayProxyEvent
): Promise<APIGatewayProxyResult> =>
  Promise.resolve()
    .then(() => {
      const payload = wh.verify(event.body, {
        "svix-id": event.headers["svix-id"] || event.headers["Svix-Id"],
        "svix-signature":
          event.headers["svix-signature"] || event.headers["Svix-Signature"],
        "svix-timestamp":
          event.headers["svix-timestamp"] || event.headers["Svix-Timestamp"],
      }) as { data?: Record<string, string>; type?: string };
      if (payload.type && payload.type !== "user.created") {
        return emptyResponse(event);
      }
      const data = (payload.data || payload) as {
        id: string;
        first_name: string;
        last_name: string;
        email_addresses: { id: string; email_address: string }[];
        primary_email_address_id: string;
        private_metadata: { stripeId?: string };
      };
      const {
        id,
        first_name,
        last_name,
        email_addresses,
        primary_email_address_id,
        private_metadata,
      } = data;
      if (private_metadata.stripeId) {
        return emptyResponse(event);
      }
      const { encrypted: token } = generateToken();
      const email = email_addresses.find(
        (e) => e.id === primary_email_address_id
      ).email_address;
      return stripe.customers
        .list({
          email,
        })
        .then((existingCustomers) =>
          existingCustomers.data.length
            ? Promise.resolve(existingCustomers.data[0])
            : stripe.customers.create({
                email,
                name: `${first_name} ${last_name}`,
              })
        )
        .then((r) =>
          axios
            .get(
              `https://api.convertkit.com/v3/subscribers?api_secret=${ckApiSecret}&email_address=${email}`
            )
            .then((ck) =>
              ck.data.total_subscribers > 0
                ? ck.data.subscribers[0].id
                : axios
                    .post(
                      "https://api.convertkit.com/v3/forms/2239289/subscribe",
                      {
                        api_secret: ckApiSecret,
                        email,
                      }
                    )
                    .then((sub) => sub.data.subscription.subscriber.id)
            )
            .then((convertKit) => ({
              stripeId: r.id,
              convertKit,
            }))
            .catch((e) => {
              console.error(e);
              return {
                stripeId: r.id,
              };
            })
        )
        .then((d) =>
          users.updateUser(id, {
            privateMetadata: { ...d, token },
          })
        )
        .then((user) =>
          ses
            .sendEmail({
              Destination: {
                ToAddresses: [email],
              },
              Message: {
                Subject: {
                  Charset: "UTF-8",
                  Data: "Welcome to RoamJS!",
                },
                Body: {
                  Html: {
                    Charset: "UTF-8",
                    Data: `<div>
<p>Welcome ${first_name}!</p>
<br>
<p>Thanks for signing up for RoamJS!</p>
<p>You already had access to the many free to use Roam extensions offered by RoamJS, which could be found <a href="https://roamjs.com/extensions">here.</a> Now with a RoamJS account, you have access to <b>premium</b> RoamJS services to really get the most out of your Roam graph. Browse through the available extensions and see which ones excite you!</p>
<p>You have also been automatically subscribed to the RoamJS Digest, where you'll receive the latest news and updates on all things RoamJS. To unsubscribe, you could visit your <a href="https://roamjs.com/user">user page</a>.</p>
<p>If you have any questions, always feel free to reach out <a href="mailto:[email protected]">[email protected].</a></p>
<p>Excited to have you join the rest of Roam's power users!</p>
<br>
<p>Best,</p>
<p>RoamJS</p>
</div>`,
                  },
                },
              },
              Source: "[email protected]",
            })
            .promise()
            .then(() => user)
        )
        .then((user) =>
          ses
            .sendEmail({
              Destination: {
                ToAddresses: ["[email protected]"],
              },
              Message: {
                Body: {
                  Text: {
                    Charset: "UTF-8",
                    Data: `${first_name} ${last_name} just signed up on RoamJS!

Make sure they are linked to a stripe customer here: https://dashboard.clerk.dev/instances/${process.env.CLERK_INSTANCE_ID}/users/${user.id}`,
                  },
                },
                Subject: {
                  Charset: "UTF-8",
                  Data: "New user signed up on RoamJS!",
                },
              },
              Source: "[email protected]",
            })
            .promise()
        )
        .then(() => bareSuccessResponse(event));
    })
    .catch(emailCatch("Customer Creation Webhook Failed", event))
Example #26
Source File: handler.ts    From antibody-web with MIT License 4 votes vote down vote up
baseHandler = async (
  event: APIGatewayEvent
): Promise<APIGatewayProxyResult> => {
  const UPLOAD_BUCKET: string = process.env.UPLOAD_BUCKET as string;
  const ML_API_BASE: string = process.env.ML_API_BASE as string;
  const DYNAMO_TABLE: string = process.env.DYNAMO_TABLE as string;

  const guid = event.requestContext.authorizer?.principalId;
  const predictionEndpoint = `${ML_API_BASE}/${config.modelPath}`;

  logger.info("Interpreting result for user with guid:", guid);

  if (!guid) {
    logger.error("No guid available in request context");
    return {
      statusCode: 400,
      body: JSON.stringify({
        error: "Missing user id",
      }),
      headers: config.defaultHeaders,
    };
  }

  const { error: envError } = validateInterpretEnvironment(process.env);

  if (envError) {
    logger.error("Environment not configured correctly", envError);
    return {
      statusCode: 400,
      body: JSON.stringify({
        error: "Environment configuration error",
      }),
      headers: config.defaultHeaders,
    };
  }

  let fileStream: Readable;

  logger.info("Retrieving user's image from S3");
  try {
    fileStream = getFileStream(UPLOAD_BUCKET, guid);
  } catch (error) {
    logger.error("Could not get image from S3", error);
    return {
      statusCode: 404,
      body: JSON.stringify({
        error: "Could not retrieve user image",
      }),
      headers: config.defaultHeaders,
    };
  }

  try {
    logger.info("Sending image to prediction endpoint" + predictionEndpoint);

    const prediction = await mlApi.interpretResult({ guid, fileStream });

    logger.info("Received prediction - updating user's info.");

    // Get our users record to update with the prediction
    const oldRecord = (await getTestRecord(DYNAMO_TABLE, guid)) as TestRecord;

    let newRecord: TestRecord = {
      ...oldRecord,
      predictionData: prediction,
      testCompleted: prediction.success,
      result: prediction.result,
    };

    logger.debug(newRecord);
    await putTestRecord(DYNAMO_TABLE, newRecord);
    logger.info("User record updated, interpreting complete");

    if (newRecord.predictionData?.success) {
      const isAwaitingReview = await reviewIfRequired(newRecord);
      logger.info(
        `${
          isAwaitingReview
            ? "Result flagged for review"
            : "Result not flagged for review"
        }`
      );
      newRecord.review = {
        status: isAwaitingReview ? "awaiting_review" : "not_reviewed",
        originalResult: newRecord.result!,
      };
    }

    return {
      statusCode: 200,
      body: JSON.stringify({
        testRecord: newRecord,
      }),
      headers: config.defaultHeaders,
    };
  } catch (error) {
    logger.error("Prediction failed", error);
    throw error;
  }
}
Example #27
Source File: sponsorships_post.ts    From roamjs-com with MIT License 4 votes vote down vote up
handler = async (
  event: APIGatewayProxyEvent
): Promise<APIGatewayProxyResult> => {
  const { value, isMonthly, source } = JSON.parse(event.body);
  if (!value) {
    return {
      statusCode: 400,
      body: "Missing sponsorship amount.",
      headers: headers(event),
    };
  }

  const user = await getClerkUser(event);
  if (!user) {
    return {
      statusCode: 401,
      body: "No Active Session",
      headers: headers(event),
    };
  }
  const reqHeaders = event.headers;
  const origin = reqHeaders.Origin || reqHeaders.origin;
  const customer = user.privateMetadata.stripeId as string;
  const email = user.emailAddresses.find(
    (e) => e.id === user.primaryEmailAddressId
  )?.emailAddress;

  if (!customer) {
    return {
      statusCode: 401,
      body: `No Stripe Customer Found with ${email}`,
      headers: headers(event),
    };
  }
  const paymentMethod = await stripe.customers
    .retrieve(customer)
    .then((c) => c as Stripe.Customer)
    .then((c) => c.invoice_settings?.default_payment_method as string);
  const owner = await dynamo
    .getItem({
      TableName,
      Key: { id: { S: source } },
    })
    .promise()
    .then((r) => r.Item?.user?.S);
  const connectedAccount = owner
    ? await users.getUser(owner).then((u) => ({
        email: u.emailAddresses.find((e) => e.id === u.primaryEmailAddressId)
          ?.emailAddress,
        stripeAccount: u.privateMetadata?.stripeAccount as string,
        thankyou: `${u.firstName} ${u.lastName}`,
      }))
    : { email: "[email protected]", stripeAccount: "", thankyou: "RoamJS" };
  const isConnected =
    connectedAccount.stripeAccount &&
    connectedAccount.email !== "[email protected]";
  if (isConnected)
    await emailError(
      "User sponsored without Stripe Account",
      new Error(
        `User ${connectedAccount.email} would have been sponored $${value} ${
          isMonthly ? "monthly" : "once"
        } but didn't have Stripe setup. Let them know!`
      )
    );
  const product = await stripe.products
    .list()
    .then((ps) => ps.data.find((p) => p.name === "RoamJS Sponsor")?.id);
  if (!product) {
    return {
      statusCode: 400,
      body: `No product found with name "RoamJS Sponsor"`,
      headers: headers(event),
    };
  }

  const price = await stripe.prices
    .list({ product })
    .then((r) =>
      r.data.find(
        (p) =>
          (p.type === "recurring" && isMonthly) ||
          (p.type === "one_time" && !isMonthly)
      )
    );

  if (isMonthly) {
    const roamjsSubscription = await stripe.subscriptions
      .list({ customer })
      .then((all) => all.data.find((s) => s.metadata.project === "RoamJS"));
    if (roamjsSubscription && !isConnected) {
      return stripe.subscriptionItems
        .create({
          subscription: roamjsSubscription.id,
          price: price.id,
          quantity: value * 125,
        })
        .then(() => ({
          statusCode: 200,
          body: JSON.stringify({ active: true, id: roamjsSubscription.id }),
          headers: headers(event),
        }));
    }
    return paymentMethod
      ? stripe.subscriptions
          .create({
            customer,
            items: [{ price: price.id, quantity: value * 125 }],
            ...(connectedAccount.stripeAccount
              ? {
                  application_fee_percent: 10,
                  transfer_data: {
                    destination: connectedAccount.stripeAccount,
                  },
                  metadata: { source },
                }
              : { metadata: { project: "RoamJS", source } }),
          })
          .then((s) => ({
            statusCode: 200,
            body: JSON.stringify({ active: true, id: s.id }),
            headers: headers(event),
          }))
          .catch((e) => ({
            statusCode: 500,
            body: `Failed to create subscription: ${
              e.errorMessage || e.message
            }`,
            headers: headers(event),
          }))
      : stripe.checkout.sessions
          .create({
            customer,
            payment_method_types: ["card"],
            line_items: [
              {
                price: price.id,
                quantity: value * 125,
              },
            ],
            mode: "subscription",
            success_url: `${origin}/checkout?thankyou=${connectedAccount.thankyou}`,
            cancel_url: `${origin}/contribute`,
            ...(connectedAccount.stripeAccount
              ? {
                  subscription_data: {
                    application_fee_percent: 10,
                    transfer_data: {
                      destination: connectedAccount.stripeAccount,
                    },
                  },
                }
              : { subscription_data: { metadata: { project: "RoamJS" } } }),
          })
          .then((session) => ({
            statusCode: 200,
            body: JSON.stringify({ id: session.id, active: false }),
            headers: headers(event),
          }))
          .catch((e) => ({
            statusCode: 500,
            body: `Failed to create session ${e.errorMessage || e.message}`,
            headers: headers(event),
          }));
  }

  return paymentMethod
    ? stripe.paymentIntents
        .create({
          customer,
          amount: value * 100,
          payment_method: paymentMethod,
          currency: "usd",
          ...(connectedAccount.stripeAccount
            ? {
                application_fee_amount: 30 + Math.ceil(value * 8),
                transfer_data: {
                  destination: connectedAccount.stripeAccount,
                },
              }
            : {}),
        })
        .then((p) => stripe.paymentIntents.confirm(p.id))
        .then(() => ({
          statusCode: 200,
          body: JSON.stringify({
            active: true,
          }),
          headers: headers(event),
        }))
        .catch((e) => ({
          statusCode: 500,
          body: e.errorMessage || e.message,
          headers: headers(event),
        }))
    : stripe.checkout.sessions
        .create({
          customer,
          payment_method_types: ["card"],
          payment_intent_data: {
            setup_future_usage: "off_session",
            ...(connectedAccount.stripeAccount
              ? {
                  application_fee_amount: 30 + Math.ceil(value * 8),
                  transfer_data: {
                    destination: connectedAccount.stripeAccount,
                  },
                }
              : {}),
          },
          mode: "payment",
          line_items: [
            {
              price_data: {
                currency: "usd",
                unit_amount: value * 100,
                product_data: {
                  name: "RoamJS Sponsor",
                },
              },
              quantity: 1,
            },
          ],
          metadata: { source },
          success_url: `${origin}/checkout?thankyou=${connectedAccount.thankyou}`,
          cancel_url: `${origin}/contribute`,
        })
        .then((session) => ({
          statusCode: 200,
          body: JSON.stringify({ id: session.id, active: false }),
          headers: headers(event),
        }))
        .catch((e) => ({
          statusCode: 500,
          body: e.errorMessage || e.message,
          headers: headers(event),
        }));
}