diff --git a/README.md b/README.md index 935e760..c075f4c 100644 --- a/README.md +++ b/README.md @@ -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**") \ No newline at end of file diff --git a/jest.config.ts b/jest.config.ts new file mode 100644 index 0000000..0d9419f --- /dev/null +++ b/jest.config.ts @@ -0,0 +1,8 @@ +import type { Config } from '@jest/types'; + +const config: Config.InitialOptions = { + verbose: true, + preset: 'ts-jest', +}; + +export default config; \ No newline at end of file diff --git a/package.json b/package.json index a2825da..86cbf79 100644 --- a/package.json +++ b/package.json @@ -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" -} \ No newline at end of file +} diff --git a/serverless.ts b/serverless.ts index 48912ac..b0fb17f 100644 --- a/serverless.ts +++ b/serverless.ts @@ -1,17 +1,17 @@ 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', @@ -19,9 +19,15 @@ const serverlessConfiguration: AWS = { }, }, // import the function via paths - functions: { hello }, + functions: { + getProductsList, + getProductsById + }, package: { individually: true }, custom: { + autoswagger:{ + useStage: true + }, esbuild: { bundle: true, minify: false, @@ -31,7 +37,7 @@ const serverlessConfiguration: AWS = { define: { 'require.resolve': undefined }, platform: 'node', concurrency: 10, - }, + } }, }; diff --git a/src/errors/http-error.class.ts b/src/errors/http-error.class.ts new file mode 100644 index 0000000..c7bcab7 --- /dev/null +++ b/src/errors/http-error.class.ts @@ -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; + } +} \ No newline at end of file diff --git a/src/functions/hello/handler.ts b/src/functions/hello/handler.ts deleted file mode 100644 index 2274ac2..0000000 --- a/src/functions/hello/handler.ts +++ /dev/null @@ -1,14 +0,0 @@ -import type { ValidatedEventAPIGatewayProxyEvent } from '@libs/api-gateway'; -import { formatJSONResponse } from '@libs/api-gateway'; -import { middyfy } from '@libs/lambda'; - -import schema from './schema'; - -const hello: ValidatedEventAPIGatewayProxyEvent = async (event) => { - return formatJSONResponse({ - message: `Hello, welcome to the exciting Serverless world!`, - event, - }); -}; - -export const main = middyfy(hello); diff --git a/src/functions/hello/index.ts b/src/functions/hello/index.ts deleted file mode 100644 index 7671512..0000000 --- a/src/functions/hello/index.ts +++ /dev/null @@ -1,19 +0,0 @@ -import schema from './schema'; -import { handlerPath } from '@libs/handler-resolver'; - -export default { - handler: `${handlerPath(__dirname)}/handler.main`, - events: [ - { - http: { - method: 'get', - path: 'hello', - request: { - schemas: { - 'application/json': schema, - }, - }, - }, - }, - ], -}; diff --git a/src/functions/hello/mock.json b/src/functions/hello/mock.json deleted file mode 100644 index 6b1c818..0000000 --- a/src/functions/hello/mock.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "headers": { - "Content-Type": "application/json" - }, - "body": "{\"name\": \"Frederic\"}" -} diff --git a/src/functions/hello/schema.ts b/src/functions/hello/schema.ts deleted file mode 100644 index 1ab6f41..0000000 --- a/src/functions/hello/schema.ts +++ /dev/null @@ -1,7 +0,0 @@ -export default { - type: "object", - properties: { - name: { type: 'string' } - }, - required: ['name'] -} as const; diff --git a/src/functions/index.ts b/src/functions/index.ts deleted file mode 100644 index 109c3d4..0000000 --- a/src/functions/index.ts +++ /dev/null @@ -1 +0,0 @@ -export { default as hello } from './hello'; diff --git a/src/functions/products/handler.test.ts b/src/functions/products/handler.test.ts new file mode 100644 index 0000000..1f2c8cc --- /dev/null +++ b/src/functions/products/handler.test.ts @@ -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); +// }); +// }); \ No newline at end of file diff --git a/src/functions/products/handler.ts b/src/functions/products/handler.ts new file mode 100644 index 0000000..f5fd181 --- /dev/null +++ b/src/functions/products/handler.ts @@ -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 => { + 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 => { + 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()); diff --git a/src/functions/products/index.ts b/src/functions/products/index.ts new file mode 100644 index 0000000..527b2e8 --- /dev/null +++ b/src/functions/products/index.ts @@ -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' + } + } + }, + }, + ], +}; diff --git a/src/functions/products/mock.json b/src/functions/products/mock.json new file mode 100644 index 0000000..c47adf1 --- /dev/null +++ b/src/functions/products/mock.json @@ -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\"}]" +} diff --git a/src/libs/api-gateway.ts b/src/libs/api-gateway.ts index ee7370c..9c7fae0 100644 --- a/src/libs/api-gateway.ts +++ b/src/libs/api-gateway.ts @@ -4,9 +4,20 @@ import type { FromSchema } from "json-schema-to-ts"; type ValidatedAPIGatewayProxyEvent = Omit & { body: FromSchema } export type ValidatedEventAPIGatewayProxyEvent = Handler, APIGatewayProxyResult> -export const formatJSONResponse = (response: Record) => { +export const formatJSONResponse = (response: Record | Record[]) => { return { statusCode: 200, body: JSON.stringify(response) } } + +export const formatErrorResponse = (statusCode: number, message: string) => { + return { + statusCode, + body: JSON.stringify({ + error: { + message, + }, + }), + }; +}; diff --git a/src/types/api-types.d.ts b/src/types/api-types.d.ts new file mode 100644 index 0000000..a4c49ec --- /dev/null +++ b/src/types/api-types.d.ts @@ -0,0 +1,7 @@ +export interface Product { + count: number; + description: string; + id: string; + price: number; + title: string; +} diff --git a/src/utils/productList.json b/src/utils/productList.json new file mode 100644 index 0000000..64d6b27 --- /dev/null +++ b/src/utils/productList.json @@ -0,0 +1,79 @@ +[ + { + "count": 4, + "description": "Short Product Description10", + "id": "7562ec4b-b13c-45c5-9b45-fc73c44a80ba", + "price": 2.2, + "title": "LastProduct1" + }, + { + "count": 3, + "description": "Short Product Description1", + "id": "7567ec4b-b13c-48c5-9d45-fc73c48a80aa", + "price": 2.2, + "title": "ProductUpdated" + }, + { + "count": 2, + "description": "Short Product Description2", + "id": "7563ec4b-b13c-48c5-9d45-fc71c48a80aa", + "price": 2, + "title": "ProductUpdated2" + }, + { + "count": 4, + "description": "Short Product Description1", + "id": "7567ec4b-b10c-48c5-9345-fc73c48a80aa", + "price": 2.4, + "title": "ProductOne" + }, + { + "count": 6, + "description": "Short Product Description3", + "id": "7567ec4b-b10c-48c5-9345-fc73c48a80a0", + "price": 10, + "title": "ProductNew" + }, + { + "count": 7, + "description": "Short Product Description2", + "id": "7567ec4b-b10c-48c5-9345-fc73c48a80a2", + "price": 23, + "title": "ProductTop" + }, + { + "count": 12, + "description": "Short Product Description7", + "id": "7567ec4b-b10c-48c5-9345-fc73c48a80a1", + "price": 15, + "title": "ProductTitle" + }, + { + "count": 7, + "description": "Short Product Description2", + "id": "7567ec4b-b10c-48c5-9345-fc73c48a80a3", + "price": 23, + "title": "Product" + }, + { + "count": 8, + "description": "Short Product Description4", + "id": "7567ec4b-b10c-48c5-9345-fc73348a80a1", + "price": 15, + "title": "ProductTest" + }, + { + "count": 2, + "description": "Short Product Descriptio1", + "id": "7567ec4b-b10c-48c5-9445-fc73c48a80a2", + "price": 23, + "title": "Product2" + }, + { + "count": 3, + "description": "Short Product Description7", + "id": "7567ec4b-b10c-45c5-9345-fc73c48a80a1", + "price": 15, + "title": "ProductName" + } +] diff --git a/swagger/swagger.js b/swagger/swagger.js new file mode 100644 index 0000000..2d81320 --- /dev/null +++ b/swagger/swagger.js @@ -0,0 +1,98 @@ +// this file was generated by serverless-auto-swagger + module.exports = { + "swagger": "2.0", + "info": { + "title": "product-service", + "version": "1" + }, + "paths": { + "/products": { + "get": { + "summary": "getProductsList", + "description": "", + "operationId": "getProductsList.get.products", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "parameters": [], + "responses": { + "200": { + "description": "Success response", + "schema": { + "$ref": "#/definitions/Product" + } + } + } + } + }, + "/products/{id}": { + "get": { + "summary": "getProductsById", + "description": "", + "operationId": "getProductsById.get.products/{id}", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "Success response", + "schema": { + "$ref": "#/definitions/Product" + } + } + } + } + } + }, + "definitions": { + "Product": { + "properties": { + "count": { + "title": "Product.count", + "type": "number" + }, + "description": { + "title": "Product.description", + "type": "string" + }, + "id": { + "title": "Product.id", + "type": "string" + }, + "price": { + "title": "Product.price", + "type": "number" + }, + "title": { + "title": "Product.title", + "type": "string" + } + }, + "required": [ + "count", + "description", + "id", + "price", + "title" + ], + "additionalProperties": false, + "title": "Product", + "type": "object" + } + }, + "securityDefinitions": {} +}; \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json index 896f946..5f3407c 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -8,7 +8,9 @@ "removeComments": true, "sourceMap": true, "target": "ES2020", - "outDir": "lib" + "outDir": "lib", + "resolveJsonModule": true, + "allowSyntheticDefaultImports": true }, "include": ["src/**/*.ts", "serverless.ts"], "exclude": [