Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 5 additions & 91 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,95 +1,9 @@
# Serverless - AWS Node.js Typescript
## shop-api-serverless

This project has been generated using the `aws-nodejs-typescript` template from the [Serverless framework](https://www.serverless.com/).
### Products

For detailed instructions, please refer to the [documentation](https://www.serverless.com/framework/docs/providers/aws/).
**GET** [**List of products**](https://8ioa6ypaxe.execute-api.us-east-1.amazonaws.com/dev/products "List of products") - /products

## Installation/deployment instructions
**GET** [**Product by id**](https://8ioa6ypaxe.execute-api.us-east-1.amazonaws.com/dev/products/7562ec4b-b13c-45c5-9b45-fc73c44a80ba "Product by id") - /products/{id}

Depending on your preferred package manager, follow the instructions below to deploy your project.

> **Requirements**: NodeJS `lts/fermium (v.14.15.0)`. If you're using [nvm](https://github.com/nvm-sh/nvm), run `nvm use` to ensure you're using the same Node version in local and in your lambda's runtime.

### Using NPM

- Run `npm i` to install the project dependencies
- Run `npx sls deploy` to deploy this stack to AWS

### Using Yarn

- Run `yarn` to install the project dependencies
- Run `yarn sls deploy` to deploy this stack to AWS

## Test your service

This template contains a single lambda function triggered by an HTTP request made on the provisioned API Gateway REST API `/hello` route with `POST` method. The request body must be provided as `application/json`. The body structure is tested by API Gateway against `src/functions/hello/schema.ts` JSON-Schema definition: it must contain the `name` property.

- requesting any other path than `/hello` with any other method than `POST` will result in API Gateway returning a `403` HTTP error code
- sending a `POST` request to `/hello` with a payload **not** containing a string property named `name` will result in API Gateway returning a `400` HTTP error code
- sending a `POST` request to `/hello` with a payload containing a string property named `name` will result in API Gateway returning a `200` HTTP status code with a message saluting the provided name and the detailed event processed by the lambda

> :warning: As is, this template, once deployed, opens a **public** endpoint within your AWS account resources. Anybody with the URL can actively execute the API Gateway endpoint and the corresponding lambda. You should protect this endpoint with the authentication method of your choice.

### Locally

In order to test the hello function locally, run the following command:

- `npx sls invoke local -f hello --path src/functions/hello/mock.json` if you're using NPM
- `yarn sls invoke local -f hello --path src/functions/hello/mock.json` if you're using Yarn

Check the [sls invoke local command documentation](https://www.serverless.com/framework/docs/providers/aws/cli-reference/invoke-local/) for more information.

### Remotely

Copy and replace your `url` - found in Serverless `deploy` command output - and `name` parameter in the following `curl` command in your terminal or in Postman to test your newly deployed application.

```
curl --location --request POST 'https://myApiEndpoint/dev/hello' \
--header 'Content-Type: application/json' \
--data-raw '{
"name": "Frederic"
}'
```

## Template features

### Project structure

The project code base is mainly located within the `src` folder. This folder is divided in:

- `functions` - containing code base and configuration for your lambda functions
- `libs` - containing shared code base between your lambdas

```
.
├── src
│ ├── functions # Lambda configuration and source code folder
│ │ ├── hello
│ │ │ ├── handler.ts # `Hello` lambda source code
│ │ │ ├── index.ts # `Hello` lambda Serverless configuration
│ │ │ ├── mock.json # `Hello` lambda input parameter, if any, for local invocation
│ │ │ └── schema.ts # `Hello` lambda input event JSON-Schema
│ │ │
│ │ └── index.ts # Import/export of all lambda configurations
│ │
│ └── libs # Lambda shared code
│ └── apiGateway.ts # API Gateway specific helpers
│ └── handlerResolver.ts # Sharable library for resolving lambda handlers
│ └── lambda.ts # Lambda middleware
├── package.json
├── serverless.ts # Serverless service file
├── tsconfig.json # Typescript compiler configuration
├── tsconfig.paths.json # Typescript paths
└── webpack.config.js # Webpack configuration
```

### 3rd party libraries

- [json-schema-to-ts](https://github.com/ThomasAribart/json-schema-to-ts) - uses JSON-Schema definitions used by API Gateway for HTTP request validation to statically generate TypeScript types in your lambda's handler code base
- [middy](https://github.com/middyjs/middy) - middleware engine for Node.Js lambda. This template uses [http-json-body-parser](https://github.com/middyjs/middy/tree/master/packages/http-json-body-parser) to convert API Gateway `event.body` property, originally passed as a stringified JSON, to its corresponding parsed object
- [@serverless/typescript](https://github.com/serverless/typescript) - provides up-to-date TypeScript definitions for your `serverless.ts` service file

### Advanced usage

Any tsconfig.json can be used, but if you do, set the environment variable `TS_NODE_CONFIG` for building the application, eg `TS_NODE_CONFIG=./tsconfig.app.json npx serverless webpack`
**GET** [**Swagger documentation**](https://f6io7dyywb.execute-api.us-east-1.amazonaws.com/dev/swagger "**Swagger documentation**")
8 changes: 8 additions & 0 deletions jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import type { Config } from '@jest/types';

const config: Config.InitialOptions = {
verbose: true,
preset: 'ts-jest',
};

export default config;
12 changes: 9 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,33 @@
"description": "Serverless aws-nodejs-typescript template",
"main": "serverless.ts",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "jest"
},
"engines": {
"node": ">=14.15.0"
},
"dependencies": {
"@middy/core": "^2.5.3",
"@middy/http-json-body-parser": "^2.5.3"
"@middy/http-cors": "^3.1.0",
"@middy/http-json-body-parser": "^2.5.3",
"serverless-auto-swagger": "^2.8.2"
},
"devDependencies": {
"@serverless/typescript": "^3.0.0",
"@types/aws-lambda": "^8.10.71",
"@types/jest": "^28.1.6",
"@types/node": "^14.14.25",
"esbuild": "^0.14.11",
"jest": "^28.1.3",
"json-schema-to-ts": "^1.5.0",
"serverless": "^3.0.0",
"serverless-esbuild": "^1.23.3",
"serverless-offline": "^8.8.1",
"ts-jest": "^28.0.7",
"ts-node": "^10.4.0",
"tsconfig-paths": "^3.9.0",
"typescript": "^4.1.3"
},
"author": "The serverless webpack authors (https://github.com/elastic-coders/serverless-webpack)",
"license": "MIT"
}
}
16 changes: 11 additions & 5 deletions serverless.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,33 @@
import type { AWS } from '@serverless/typescript';

import hello from '@functions/hello';
import {getProductsList, getProductsById} from '@functions/products';

const serverlessConfiguration: AWS = {
service: 'product-service',
frameworkVersion: '3',
plugins: ['serverless-esbuild'],
plugins: ['serverless-auto-swagger', 'serverless-offline','serverless-esbuild'],
provider: {
name: 'aws',
runtime: 'nodejs14.x',
apiGateway: {
minimumCompressionSize: 1024,
shouldStartNameWithService: true,
shouldStartNameWithService: true
},
environment: {
AWS_NODEJS_CONNECTION_REUSE_ENABLED: '1',
NODE_OPTIONS: '--enable-source-maps --stack-trace-limit=1000',
},
},
// import the function via paths
functions: { hello },
functions: {
getProductsList,
getProductsById
},
package: { individually: true },
custom: {
autoswagger:{
useStage: true
},
esbuild: {
bundle: true,
minify: false,
Expand All @@ -31,7 +37,7 @@ const serverlessConfiguration: AWS = {
define: { 'require.resolve': undefined },
platform: 'node',
concurrency: 10,
},
}
},
};

Expand Down
11 changes: 11 additions & 0 deletions src/errors/http-error.class.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export class HTTPError extends Error {
statusCode: number;
context?: string;

constructor(statusCode: number, message: string, context?: string) {
super(message);
this.statusCode = statusCode;
this.message = message;
this.context = context;
}
}
14 changes: 0 additions & 14 deletions src/functions/hello/handler.ts

This file was deleted.

19 changes: 0 additions & 19 deletions src/functions/hello/index.ts

This file was deleted.

6 changes: 0 additions & 6 deletions src/functions/hello/mock.json

This file was deleted.

7 changes: 0 additions & 7 deletions src/functions/hello/schema.ts

This file was deleted.

1 change: 0 additions & 1 deletion src/functions/index.ts

This file was deleted.

22 changes: 22 additions & 0 deletions src/functions/products/handler.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// import { getProductsList } from './handler';
// import { default as products } from '../../utils/productList.json';

// jest.mock('@libs/api-gateway', () => ({
// formatJSONResponse: (arg) => arg
// }));

// jest.mock('@libs/lambda', () => ({
// middyfy: (arg) => arg
// }));

// describe('getProductList', () => {
// it('should return productList', async () => {
// // Act
// const result: any = await getProductsList('');

// console.log('result', result);

// // Assert
// expect(result.data).toEqual(products);
// });
// });
38 changes: 38 additions & 0 deletions src/functions/products/handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda";
import { formatErrorResponse, formatJSONResponse } from '@libs/api-gateway';
import { middyfy } from '@libs/lambda';
import { default as products } from '../../utils/productList.json';
import cors from '@middy/http-cors';
import { HTTPError } from "src/errors/http-error.class";

export const getProductsList = middyfy(async (): Promise<APIGatewayProxyResult> => {
try {
return formatJSONResponse(products);
} catch (e) {
if (e instanceof HTTPError) {
return formatErrorResponse(e.statusCode, e.message);
}

return formatErrorResponse(500, `Failed to get products: ${e.message}`);
}
}).use(cors());

export const getProductsById = middyfy(async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
try {
const id = event.pathParameters.id;
if (!id) {
throw new HTTPError(400, 'Product id is not correct');
}
const product = products.find(p => p.id === id);
if (!product) {
throw new HTTPError(404, 'Product not found');
}
return formatJSONResponse(product);
} catch (error) {
if (error instanceof HTTPError) {
return formatErrorResponse(error.statusCode, error.message);
}

return formatErrorResponse(500, error.message);
}
}).use(cors());
43 changes: 43 additions & 0 deletions src/functions/products/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { handlerPath } from '@libs/handler-resolver';

export const getProductsList = {
handler: `${handlerPath(__dirname)}/handler.getProductsList`,
events: [
{
http: {
method: 'get',
path: 'products',
cors: {
origin: '*'
},
responses: {
'200': {
description: 'Success response',
bodyType: 'Product'
}
}
},
},
],
};

export const getProductsById = {
handler: `${handlerPath(__dirname)}/handler.getProductsById`,
events: [
{
http: {
method: 'get',
path: 'products/{id}',
cors: {
origin: '*'
},
responses: {
'200': {
description: 'Success response',
bodyType: 'Product'
}
}
},
},
],
};
6 changes: 6 additions & 0 deletions src/functions/products/mock.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"headers": {
"Content-Type": "application/json"
},
"body": "[{\"count\":3,\"description\":\"ShortProductDescription1\",\"id\":\"7567ec4b-b13c-48c5-9d45-fc73c48a80aa\",\"price\":2.2,\"title\":\"ProductUpdated\"},{\"count\":2,\"description\":\"ShortProductDescription2\",\"id\":\"7563ec4b-b13c-48c5-9d45-fc71c48a80aa\",\"price\":2,\"title\":\"ProductUpdated2\"},{\"count\":4,\"description\":\"ShortProductDescription1\",\"id\":\"7567ec4b-b10c-48c5-9345-fc73c48a80aa\",\"price\":2.4,\"title\":\"ProductOne\"},{\"count\":6,\"description\":\"ShortProductDescription3\",\"id\":\"7567ec4b-b10c-48c5-9345-fc73c48a80a0\",\"price\":10,\"title\":\"ProductNew\"},{\"count\":7,\"description\":\"ShortProductDescription2\",\"id\":\"7567ec4b-b10c-48c5-9345-fc73c48a80a2\",\"price\":23,\"title\":\"ProductTop\"},{\"count\":12,\"description\":\"ShortProductDescription7\",\"id\":\"7567ec4b-b10c-48c5-9345-fc73c48a80a1\",\"price\":15,\"title\":\"ProductTitle\"},{\"count\":7,\"description\":\"ShortProductDescription2\",\"id\":\"7567ec4b-b10c-48c5-9345-fc73c48a80a3\",\"price\":23,\"title\":\"Product\"},{\"count\":8,\"description\":\"ShortProductDescription4\",\"id\":\"7567ec4b-b10c-48c5-9345-fc73348a80a1\",\"price\":15,\"title\":\"ProductTest\"},{\"count\":2,\"description\":\"ShortProductDescriptio1\",\"id\":\"7567ec4b-b10c-48c5-9445-fc73c48a80a2\",\"price\":23,\"title\":\"Product2\"},{\"count\":3,\"description\":\"ShortProductDescription7\",\"id\":\"7567ec4b-b10c-45c5-9345-fc73c48a80a1\",\"price\":15,\"title\":\"ProductName\"}]"
}
13 changes: 12 additions & 1 deletion src/libs/api-gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,20 @@ import type { FromSchema } from "json-schema-to-ts";
type ValidatedAPIGatewayProxyEvent<S> = Omit<APIGatewayProxyEvent, 'body'> & { body: FromSchema<S> }
export type ValidatedEventAPIGatewayProxyEvent<S> = Handler<ValidatedAPIGatewayProxyEvent<S>, APIGatewayProxyResult>

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

export const formatErrorResponse = (statusCode: number, message: string) => {
return {
statusCode,
body: JSON.stringify({
error: {
message,
},
}),
};
};
Loading