feat: sc 121 - serverless boilerplate (#140)

* chore: init for redoing aws stack base

* chore: fix tsc build errors

* chore: remove comment, remove schema verif that was causing error, add context

* chore: replace serverless.ts with serverless.yaml

* chore: rename serverless file correctly

* chore: fix deployment errors

* chore: add serverless-offline

* chore: fix bug executing function

* chore: readme for aws

* chore: rename to kebab-case and add eslint rule for it

* chore: add aws cred link to serverless readme
This commit is contained in:
Janison Sivarajah 2023-04-04 14:42:51 -04:00 committed by GitHub
parent 0754606089
commit 9e202f0a1f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 5254 additions and 3 deletions

View File

@ -16,4 +16,8 @@ contracts/out
subgraph/abis
subgraph/build
subgraph/generated
subgraph/examples/query/.graphclient
subgraph/examples/query/.graphclient
serverless/dist
serverless/.serverless
serverless/.esbuild

View File

@ -12,8 +12,22 @@ module.exports = {
'./ui/tsconfig.json',
'./subgraph/tsconfig.json',
'./subgraph/tsconfig.tools.json',
'./serverless/tsconfig.json',
],
},
plugins: ['@typescript-eslint', 'prettier'],
plugins: ['@typescript-eslint', 'prettier', 'filenames-simple'],
root: true,
overrides: [
{
files: ['*.ts'],
rules: {
'filenames-simple/naming-convention': [
'error',
{
rule: 'kebab-case',
},
],
},
},
],
};

View File

@ -9,4 +9,8 @@ contracts/out/**/*
subgraph/abis/**/*
subgraph/build/**/*
subgraph/generated/**/*
subgraph/examples/query/.graphclient/**/*
subgraph/examples/query/.graphclient/**/*
serverless/dist/**/*
serverless/.serverless/**/*
serverless/.esbuild/**/*

View File

@ -26,6 +26,7 @@
"@typescript-eslint/parser": "^5.54.1",
"eslint": "^8.35.0",
"eslint-config-prettier": "^8.7.0",
"eslint-plugin-filenames-simple": "^0.8.0",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-simple-import-sort": "^10.0.0",
"husky": "^8.0.2",

12
serverless/.gitignore vendored Normal file
View File

@ -0,0 +1,12 @@
# package directories
node_modules
jspm_packages
# Serverless directories
.serverless
# esbuild directories
.esbuild
# output
dist

38
serverless/README.md Normal file
View File

@ -0,0 +1,38 @@
## NFA - Serverless
### Requirements
This sub-project of NFAs requires Node 18. Specifically, this has been tested with 18.13.0 so far.
### Setup
After cloning the repo, ensure you run `yarn` in the root directory. After that, `cd` into the `serverless` directory and alsy run `yarn`.
If you are deploying, make sure you have your AWS credentials set to environment variables or have setup AWS credentials using the AWS CLI. Please refer to the official AWS documentation [here](https://www.serverless.com/framework/docs/providers/aws/guide/credentials/) to see all the ways to set these credentials.
Basically, these values need to be set:
```
export AWS_ACCESS_KEY_ID=value
export AWS_SECRET_ACCESS_KEY=value
export AWS_SESSION_TOKEN=value
```
You can get these from the main screen after logging in.
### Running and Testing
You first build the code by running `yarn build`. This will produce the bundle file in the `dist` directory.
TODO: `yarn test`
To run locally, use `SLS_DEBUG=* yarn sls offline --verbose`. You can then hit the endpoints displayed in the console using curl, postman or any HTTP client.
### Deploying
To deploy, make sure you have AWS credentials set in your local environment.
To deploy to development environment:
`yarn sls deploy --stage dev`
To deploy to production environment:
`yarn sls deploy --stage prd`

33
serverless/package.json Normal file
View File

@ -0,0 +1,33 @@
{
"name": "@fleekxyz/nfa-serverless",
"version": "0.0.1",
"description": "The serverless stack for the NFA application",
"main": "index.js",
"scripts": {
"build": "yarn tsc",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "fleek",
"license": "MIT",
"devDependencies": {
"@serverless/typescript": "^3.27.0",
"@types/aws-lambda": "^8.10.114",
"@types/node": "^18.15.5",
"@types/uuid": "^9.0.1",
"esbuild": "^0.17.12",
"json-schema-to-ts": "^2.7.2",
"serverless": "^3.28.1",
"serverless-esbuild": "^1.42.0",
"serverless-offline": "^12.0.4",
"ts-node": "^10.9.1",
"tsconfig-paths": "^4.1.2",
"typescript": "^5.0.2"
},
"dependencies": {
"@middy/core": "^4.2.7",
"@middy/http-json-body-parser": "^4.2.7",
"@middy/http-response-serializer": "^4.2.8",
"aws-sdk": "^2.1342.0",
"uuid": "^9.0.0"
}
}

View File

@ -0,0 +1,39 @@
service: nfa-serverless
frameworkVersion: '3'
plugins:
- serverless-esbuild
- serverless-offline
provider:
name: aws
runtime: nodejs18.x
stage: ${opt:stage, 'prd'}
region: ${opt:region, 'us-west-2'}
apiGateway:
minimumCompressionSize: 1024
shouldStartNameWithService: true
environment:
DEBUG: '*'
AWS_STAGE: ${self:provider.stage}
AWS_NODEJS_CONNECTION_REUSE_ENABLED: 1
custom:
esbuild:
bundle: true
minify: true
sourcemap: false
exclude:
- 'aws-sdk'
target: 'node18'
platform: 'node'
concurrency: 10
functions:
submitBuildInfo:
handler: dist/functions/builds/handler.submitBuildInfo
events:
- http:
path: build
method: post
cors: true

View File

@ -0,0 +1,23 @@
import { APIGatewayProxyResult } from 'aws-lambda';
import { formatJSONResponse } from '@libs/api-gateway';
import { v4 } from 'uuid';
export const submitBuildInfo = async (): Promise<APIGatewayProxyResult> => {
try {
const id = v4();
const buildInfo = {
buildId: id,
createdAt: new Date().toISOString(),
};
return formatJSONResponse({
buildInfo,
});
} catch (e) {
return formatJSONResponse({
status: 500,
message: e,
});
}
};

View File

@ -0,0 +1,13 @@
import { handlerPath } from '@libs/handler-resolver';
export const submitBuildInfo = {
handler: `${handlerPath(__dirname)}/handler.submitBuildInfo`,
events: [
{
http: {
method: 'post',
path: 'buildInfo',
},
},
],
};

View File

@ -0,0 +1,8 @@
// QUESTION: should we add back in schema verification?
export const formatJSONResponse = (response: Record<string, unknown>) => {
return {
statusCode: 200,
body: JSON.stringify(response),
};
};

View File

@ -0,0 +1,3 @@
export const handlerPath = (context: string) => {
return `${context.split(process.cwd())[1].substring(1).replace(/\\/g, '/')}`;
};

View File

@ -0,0 +1,20 @@
import middy from '@middy/core';
import middyJsonBodyParser from '@middy/http-json-body-parser';
import httpResponseSerializer from '@middy/http-response-serializer';
import { Handler } from 'aws-lambda';
export const middyfy = (handler: Handler) => {
return middy(handler)
.use(middyJsonBodyParser())
.use(
httpResponseSerializer({
defaultContentType: 'application/json',
serializers: [
{
regex: /^application\/json$/,
serializer: (res) => JSON.stringify(res.body || res),
},
],
})
);
};

27
serverless/tsconfig.json Normal file
View File

@ -0,0 +1,27 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"lib": ["ESNext"],
"moduleResolution": "node",
"noUnusedLocals": true,
"noUnusedParameters": true,
"removeComments": true,
"outDir": "dist",
"baseUrl": ".",
"paths": {
"@functions/*": ["src/functions/*"],
"@libs/*": ["src/libs/*"]
}
},
"include": ["./**/*", "src/**/*.ts", "serverless.ts"],
"exclude": [
"node_modules/**/*",
".serverless/**/*",
".webpack/**/*",
"_warmup/**/*",
".vscode/**/*"
],
"ts-node": {
"require": ["tsconfig-paths/register"]
}
}

5000
serverless/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1312,6 +1312,13 @@ eslint-config-prettier@^8.7.0:
resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-8.7.0.tgz#f1cc58a8afebc50980bd53475451df146c13182d"
integrity sha512-HHVXLSlVUhMSmyW4ZzEuvjpwqamgmlfkutD53cYXLikh4pt/modINRcCIApJ84czDxM4GZInwUrromsDdTImTA==
eslint-plugin-filenames-simple@^0.8.0:
version "0.8.0"
resolved "https://registry.yarnpkg.com/eslint-plugin-filenames-simple/-/eslint-plugin-filenames-simple-0.8.0.tgz#71fb9fc975f5e12835bf9b58fa11a06ad0933432"
integrity sha512-8+uBzNBE5gSUMQv7bmMBiOD26eKzD4/5flPtD5Vl3dzZLXotSwXK3W7ZZqKQfU0Qyoborh+LqbN76EfmbBcU8A==
dependencies:
pluralize "^8.0.0"
eslint-plugin-prettier@^4.2.1:
version "4.2.1"
resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-4.2.1.tgz#651cbb88b1dab98bfd42f017a12fa6b2d993f94b"
@ -2282,6 +2289,11 @@ pinst@^3.0.0:
resolved "https://registry.yarnpkg.com/pinst/-/pinst-3.0.0.tgz#80dec0a85f1f993c6084172020f3dbf512897eec"
integrity sha512-cengSmBxtCyaJqtRSvJorIIZXMXg+lJ3sIljGmtBGUVonMnMsVJbnzl6jGN1HkOWwxNuJynCJ2hXxxqCQrFDdw==
pluralize@^8.0.0:
version "8.0.0"
resolved "https://registry.yarnpkg.com/pluralize/-/pluralize-8.0.0.tgz#1a6fa16a38d12a1901e0320fa017051c539ce3b1"
integrity sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==
prelude-ls@^1.2.1:
version "1.2.1"
resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.2.1.tgz#debc6489d7a6e6b0e7611888cec880337d316396"