aws-lambda#APIGatewayProxyHandler TypeScript Examples

The following examples show how to use aws-lambda#APIGatewayProxyHandler. 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: versions_get.ts    From roamjs-com with MIT License 6 votes vote down vote up
handler: APIGatewayProxyHandler = async (event) => {
  const { id, limit, page } = event.queryStringParameters || {};
  const limitValue = Number(limit) || 1;
  const pageValue = Number(page) || 0;
  if (limitValue < 1) {
    return userError("Limit must be greater than 0", event);
  }
  if (pageValue < 0) {
    return userError("Page must be greater than or equal to 0", event);
  }
  if (!id) {
    return userError("Must include extension to look up versions", event);
  }
  return s3
    .listObjectsV2({ Bucket: "roamjs.com", Prefix: `${id}/`, Delimiter: "/" })
    .promise()
    .then((r) => {
      const allVersions = r.CommonPrefixes.map((c) => c.Prefix)
        .filter((s) => /\d\d\d\d-\d\d-\d\d-\d\d-\d\d/.test(s))
        .reverse();
      return {
        versions: allVersions
          .slice(pageValue, pageValue + limitValue)
          .map((s) => s.replace(id, "").replace(/\//g, "")),
        isEnd: pageValue + limitValue >= allVersions.length,
      };
    })
    .then((res) => ({
      statusCode: 200,
      body: JSON.stringify(res),
      headers,
    }))
    .catch(emailCatch(`Failed to fetch versions for ${id}`));
}
Example #2
Source File: token.ts    From nft-market-service with MIT License 6 votes vote down vote up
token: APIGatewayProxyHandler = async (event, _context) => {
  try {
    if (
      event.pathParameters?.id &&
      event.pathParameters?.id.length > 0 &&
      !JSON.stringify(tokenProps[event.pathParameters.id])
    ) {
      throw new Error('Token not found')
    }

    return {
      statusCode: 200,
      body:
        event.pathParameters?.id && event.pathParameters?.id.length > 0
          ? JSON.stringify(tokenProps[event.pathParameters.id])
          : JSON.stringify(tokenProps),
      headers: {
        'Access-Control-Allow-Origin': '*',
      },
    }
  } catch (e) {
    return {
      statusCode: 500,
      body: JSON.stringify(e),
      headers: {
        'Access-Control-Allow-Origin': '*',
      },
    }
  }
}
Example #3
Source File: ethusd.ts    From nft-market-service with MIT License 6 votes vote down vote up
ethusd: APIGatewayProxyHandler = async (_event, _context) => {
  try {
    const { APIETHERSCAN } = process.env

    const quote = await (
      await fetch(
        `https://api.etherscan.io/api?module=stats&action=ethprice&apikey=${APIETHERSCAN}`
      )
    ).json()

    return {
      statusCode: 200,
      body: JSON.stringify(quote),
      headers: {
        'Access-Control-Allow-Origin': '*',
      },
    }
  } catch (e) {
    console.log(e)

    return {
      statusCode: 500,
      body: JSON.stringify(e),
      headers: {
        'Access-Control-Allow-Origin': '*',
      },
    }
  }
}
Example #4
Source File: lambda-swagger.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
handler: APIGatewayProxyHandler = async (event, context) => {
  if (!cachedServer) {
    const server = await bootstrapServer()
    cachedServer = server
    return proxy(server, event, context, 'PROMISE').promise
  } else {
    return proxy(cachedServer, event, context, 'PROMISE').promise
  }
}
Example #5
Source File: lambda-main.ts    From mamori-i-japan-api with BSD 2-Clause "Simplified" License 6 votes vote down vote up
handler: APIGatewayProxyHandler = async (event, context) => {
  if (!cachedServer) {
    const server = await bootstrapServer()
    cachedServer = server
    return proxy(server, event, context, 'PROMISE').promise
  } else {
    return proxy(cachedServer, event, context, 'PROMISE').promise
  }
}
Example #6
Source File: index.ts    From aws-nestjs-starter with The Unlicense 6 votes vote down vote up
handler: APIGatewayProxyHandler = async (
  event,
  context,
  callback,
) => {
  if (!cachedServer) {
    cachedServer = await bootstrapServer();
  }
  return cachedServer(event, context, callback);
}
Example #7
Source File: versions_get.ts    From roamjs-com with MIT License 6 votes vote down vote up
handler: APIGatewayProxyHandler = async (event) => {
  const { id, limit, page } = event.queryStringParameters || {};
  const limitValue = Number(limit) || 1;
  const pageValue = Number(page) || 0;
  if (limitValue < 1) {
    return userError("Limit must be greater than 0", event);
  }
  if (pageValue < 0) {
    return userError("Page must be greater than or equal to 0", event);
  }
  if (!id) {
    return userError("Must include extension to look up versions", event);
  }
  return s3
    .listObjectsV2({ Bucket: "roamjs.com", Prefix: `${id}/`, Delimiter: "/" })
    .promise()
    .then((r) => {
      const allVersions = r.CommonPrefixes.map((c) => c.Prefix)
        .filter((s) => /\d\d\d\d-\d\d-\d\d-\d\d-\d\d/.test(s))
        .reverse();
      return {
        versions: allVersions
          .slice(pageValue, pageValue + limitValue)
          .map((s) => s.replace(id, "").replace(/\//g, "")),
        isEnd: pageValue + limitValue >= allVersions.length,
      };
    })
    .then((res) => ({
      statusCode: 200,
      body: JSON.stringify(res),
      headers: headers(event),
    }))
    .catch(emailCatch(`Failed to fetch versions for ${id}`, event));
}
Example #8
Source File: convertkit_post.ts    From roamjs-com with MIT License 6 votes vote down vote up
handler: APIGatewayProxyHandler = (event) =>
  getClerkEmail(event).then((email) =>
    axios
      .post("https://api.convertkit.com/v3/forms/2239289/subscribe", {
        api_secret: ckApiSecret,
        email,
      })
      .then(() => bareSuccessResponse(event))
  )
Example #9
Source File: convertkit_get.ts    From roamjs-com with MIT License 6 votes vote down vote up
handler: APIGatewayProxyHandler = (event) => {
  return getClerkEmail(event).then((email) =>
    axios
      .get(
        `https://api.convertkit.com/v3/subscribers?api_secret=${ckApiSecret}&email_address=${email}`
      )
      .then((ck) => ({
        statusCode: 200,
        body: JSON.stringify({ isSubscribed: ck.data.total_subscribers > 0 }),
        headers: headers(event),
      }))
  );
}
Example #10
Source File: convertkit_delete.ts    From roamjs-com with MIT License 6 votes vote down vote up
handler: APIGatewayProxyHandler = (event) =>
  getClerkEmail(event).then((email) =>
    axios
      .put("https://api.convertkit.com/v3/unsubscribe", {
        api_secret: ckApiSecret,
        email,
      })
      .then(() => emptyResponse(event))
  )
Example #11
Source File: handler.ts    From serverless-typescript-starter with MIT License 6 votes vote down vote up
hello: APIGatewayProxyHandler = async (event, context) => {
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: "Go Serverless v2.0! Your function executed successfully!",
      context,
      event,
    }),
  };
}
Example #12
Source File: dropbox-auth_post.ts    From roamjs-com with MIT License 6 votes vote down vote up
handler: APIGatewayProxyHandler = async (event) => {
  const data = JSON.parse(event.body || "{}");
  const params = new URLSearchParams();
  Object.keys(data).forEach((k) => params.append(k, data[k]));

  return axios
    .post("https://api.dropboxapi.com/oauth2/token", params, {
      headers: {
        Authorization: `Basic ${Buffer.from(
          `${process.env.DROPBOX_CLIENT_ID}:${process.env.DROPBOX_CLIENT_SECRET}`
        ).toString("base64")}`,
        "Content-Type": "application/x-www-form-urlencoded",
      },
    })
    .then((r) => {
      if (data.grant_type === "refresh_token") {
        return {
          statusCode: 200,
          body: JSON.stringify(r.data),
          headers,
        };
      }
      return axios
        .post(
          "https://api.dropboxapi.com/2/users/get_account",
          { account_id: r.data.account_id },
          { headers: { Authorization: `Bearer ${r.data.access_token}` } }
        )
        .then((u) => ({
          statusCode: 200,
          body: JSON.stringify({ ...r.data, label: u.data.name.display_name }),
          headers,
        }));
    })
    .catch((e) => ({
      statusCode: 500,
      body: JSON.stringify(e.response?.data || { message: e.message }),
      headers,
    }));
}
Example #13
Source File: listLikesForPhoto.ts    From dynamodb-instagram with MIT License 6 votes vote down vote up
main: APIGatewayProxyHandler = async (event: APIGatewayProxyEvent) => {
    const { photoId } = event.pathParameters
    const likes = await listLikesForPhoto(photoId)
    const response = {
        statusCode: 200,
        body: JSON.stringify({
           likes 
        })
    }

    return response
}
Example #14
Source File: listFollowedByUser.ts    From dynamodb-instagram with MIT License 6 votes vote down vote up
main: APIGatewayProxyHandler = async (event: APIGatewayProxyEvent) => {
    const { username } = event.pathParameters
    const following = await listFollowedByUser(username)
    const response = {
        statusCode: 200,
        body: JSON.stringify({
            following
        })
    }

    return response
}
Example #15
Source File: function.ts    From serverless-dynamodb-api-boilerplate with MIT License 6 votes vote down vote up
handle: APIGatewayProxyHandler = async (event, _context) => {
  try {
    const result = await createController(event, documentClient);
    return httpResponse(result);
  } catch (error) {
    console.error(error);

    return httpResponse("Bad Request", 400);
  }
}
Example #16
Source File: function.ts    From serverless-dynamodb-api-boilerplate with MIT License 6 votes vote down vote up
handle: APIGatewayProxyHandler = async (event, _context) => {
  try {
    const result = await deleteController(event, documentClient);
    return httpResponse(result);
  } catch (error) {
    console.error(error);

    return httpResponse("Bad Request", 400);
  }
}
Example #17
Source File: function.ts    From serverless-dynamodb-api-boilerplate with MIT License 6 votes vote down vote up
handle: APIGatewayProxyHandler = async (event, _context) => {
  try {
    const result = await getController(event, documentClient);
    return httpResponse(result);
  } catch (error) {
    console.error(error);

    return httpResponse("Bad Request", 400);
  }
}
Example #18
Source File: commentOnPhoto.ts    From dynamodb-instagram with MIT License 6 votes vote down vote up
main: APIGatewayProxyHandler = async (event: APIGatewayProxyEvent) => {
    const { username, photoId } = event.pathParameters
    const photo = new Photo(username, "", photoId)
    const { commentingUsername, content } = JSON.parse(event.body)
    const comment = await commentOnPhoto(photo, commentingUsername, content)
    const response = {
        statusCode: 200,
        body: JSON.stringify({
            comment
        })
    }

    return response
}
Example #19
Source File: createPhoto.ts    From dynamodb-instagram with MIT License 6 votes vote down vote up
main: APIGatewayProxyHandler = async (event: APIGatewayProxyEvent) => {
    const { username } = event.pathParameters
    const { url } = JSON.parse(event.body)
    const photo = new Photo(username, url)
    await createPhoto(photo)
    const response = {
        statusCode: 200,
        body: JSON.stringify({
            photo
        })
    }

    return response
}
Example #20
Source File: createUser.ts    From dynamodb-instagram with MIT License 6 votes vote down vote up
main: APIGatewayProxyHandler = async (event: APIGatewayProxyEvent) => {
    const { username, name } = JSON.parse(event.body)
    const user = new User(username, name)
    await createUser(user)
    const response = {
        statusCode: 200,
        body: JSON.stringify({
            user
        })
    }

    return response
}
Example #21
Source File: followUser.ts    From dynamodb-instagram with MIT License 6 votes vote down vote up
main: APIGatewayProxyHandler = async (event: APIGatewayProxyEvent) => {
    const { username: followedUsername } = event.pathParameters
    const { followingUsername } = JSON.parse(event.body)
    const follow = await followUser(followedUsername, followingUsername)
    const response = {
        statusCode: 200,
        body: JSON.stringify({
            follow
        })
    }

    return response
}
Example #22
Source File: getPhoto.ts    From dynamodb-instagram with MIT License 6 votes vote down vote up
main: APIGatewayProxyHandler = async (event: APIGatewayProxyEvent) => {
    const { username, photoId } = event.pathParameters
    const photo = await getPhoto(username, photoId)
    const response = {
        statusCode: 200,
        body: JSON.stringify({
            photo
        })
    }

    return response
}
Example #23
Source File: getUser.ts    From dynamodb-instagram with MIT License 6 votes vote down vote up
main: APIGatewayProxyHandler = async (event: APIGatewayProxyEvent) => {
    const { username } = event.pathParameters
    const user = await getUser(username)
    const response = {
        statusCode: 200,
        body: JSON.stringify({
            user
        })
    }

    return response
}
Example #24
Source File: likePhoto.ts    From dynamodb-instagram with MIT License 6 votes vote down vote up
main: APIGatewayProxyHandler = async (event: APIGatewayProxyEvent) => {
    const { username, photoId } = event.pathParameters
    const photo = new Photo(username, "", photoId)
    const { likingUsername } = JSON.parse(event.body)
    const like = await likePhoto(photo, likingUsername )
    const response = {
        statusCode: 200,
        body: JSON.stringify({
            like
        })
    }

    return response
}
Example #25
Source File: listCommentsForPhoto.ts    From dynamodb-instagram with MIT License 6 votes vote down vote up
main: APIGatewayProxyHandler = async (event: APIGatewayProxyEvent) => {
    const { photoId } = event.pathParameters
    const comments = await listCommentsForPhoto(photoId)
    const response = {
        statusCode: 200,
        body: JSON.stringify({
          comments 
        })
    }

    return response
}
Example #26
Source File: listFollowersOfUser.ts    From dynamodb-instagram with MIT License 6 votes vote down vote up
main: APIGatewayProxyHandler = async (event: APIGatewayProxyEvent) => {
    const { username } = event.pathParameters
    const followers = await listFollowersOfUser(username)
    const response = {
        statusCode: 200,
        body: JSON.stringify({
            followers
        })
    }

    return response
}
Example #27
Source File: publish_post.ts    From roamjs-com with MIT License 5 votes vote down vote up
handler: APIGatewayProxyHandler = authenticateDeveloper(
  (event) => {
    const userId = event.headers.Authorization;
    const { path } = JSON.parse(event.body || "{}");
    return dynamo
      .query({
        TableName,
        IndexName: "user-index",
        KeyConditionExpression: "#u = :u",
        ExpressionAttributeNames: { "#u": "user" },
        ExpressionAttributeValues: { ":u": { S: userId } },
      })
      .promise()
      .then((r) => r.Items.map((i) => i.id?.S))
      .then((paths) =>
        paths.includes(path.replace(/^([^/]+)\/(.*)$/, "$1"))
          ? sts
              .assumeRole({
                RoleArn: process.env.LAMBDA_ROLE,
                DurationSeconds: 900,
                RoleSessionName: `publish-${userId}`,
                Policy: JSON.stringify({
                  Version: "2012-10-17",
                  Statement: [
                    {
                      Sid: "PutPaths",
                      Effect: "Allow",
                      Action: "s3:PutObject",
                      Resource: [`arn:aws:s3:::roamjs.com/${path}/*`],
                    },
                    {
                      Sid: "InvalidateCache",
                      Effect: "Allow",
                      Action: [
                        "cloudfront:CreateInvalidation",
                        "cloudfront:GetInvalidation",
                      ],
                      Resource: process.env.CLOUDFRONT_ARN,
                    },
                  ],
                }),
              })
              .promise()
              .then((creds) => ({
                statusCode: 200,
                body: JSON.stringify({
                  credentials: creds.Credentials,
                  distributionId: /\/(.*)$/.exec(
                    process.env.CLOUDFRONT_ARN
                  )?.[1],
                }),
                headers: headers(event),
              }))
          : userError(`User not authorized to publish to path ${path}`, event)
      );
  }
)
Example #28
Source File: lambda-helpers.ts    From roamjs-com with MIT License 5 votes vote down vote up
authenticateDeveloper =
  (handler: APIGatewayProxyHandler): APIGatewayProxyHandler =>
  (event, ctx, callback) => {
    const Authorization =
      event.headers.Authorization || event.headers.authorization || "";
    const encryptionSecret = process.env.ENCRYPTION_SECRET;
    const [email, token] = Buffer.from(
      Authorization.replace(/^Bearer /, ""),
      "base64"
    )
      .toString()
      .split(":");

    return users
      .getUserList({ emailAddress: [email] })
      .then((us) =>
        us.find((u) => {
          const stored = AES.decrypt(
            u.privateMetadata.token as string,
            encryptionSecret
          ).toString(encutf8);
          return stored && stored === token;
        })
      )
      .catch(() => undefined)
      .then((user) => {
        if (!user) {
          return {
            statusCode: 401,
            body: "Invalid Developer token",
            headers: headers(event),
          };
        }
        if (!user.publicMetadata["developer"]) {
          return {
            statusCode: 403,
            body: "User has not signed up for the RoamJS Developer extension",
            headers: headers(event),
          };
        }
        event.headers.Authorization = user.id;
        const result = handler(event, ctx, callback);
        if (!result) {
          return emptyResponse(event);
        }
        return result;
      });
  }
Example #29
Source File: handler.ts    From pdf-lambda-puppeteer with The Unlicense 5 votes vote down vote up
getPDF: APIGatewayProxyHandler = async (event, _context) => {
  const response = await PDFGenerator.getPDF(event);
  return response;
}