Introduction
This is a complete example serverless function using Typescript
Folder structure:
|-- config-env-for-serverless.js: config env variable for serverless
|-- jest.config.js: jest config file for unit test
|-- postman-collections: postman collections for this project, you can import them to Postman (includes some tests)
|-- scripts: will include some helper scripts (using in CI/CD)
|-- serverless.yml: serverless config file
|-- src
|---- const: it includes some constant variables
|---- middlewares: it includes middlewares for you projects
|---- routes: it includes your routes
|---- services: it includes your services
How to start
1. Install packages
npm i
.env
file
2. Create cp .env.example .env
And the modified the values for this file.
Please note: serverless offline (when you run the project offline) will automatically recognize .env
file
but to deploy the project successfully, you need to update all environment variables using serverless.yml
file (section: environment
)
3. Run unit test (using Jest)
npm run unit-test
4. Start the app in local (it will reload the server automatically if you change your code)
npm start
The console output will look like this
5. Run integration test local
Note: you need to keep the server running and open new terminal and run
npm run integration-test
it will run integration test with localhost
6. Run integration test after the project is deployed (dont run it in your local, it will be run in CI/CD):
Basically, when the app is deployed, we will get a api url, the integration test will run to test the api url.
npm run ci-integration-test
Deploy
a. Deploy local
Make sure that you have configured AWS files
npm run deploy
b. Deploy using Github actions
Please set all environment varibles in file .env
using Github secrets.
This project is using AWS configure credentials action, so you also need to set two secrets: AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
c. Deploy using Bitbucket
You need to set two mandatory project variables: AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
Developing
- Run unit test to see what going on
- Create new routes inside
src/routes
- Create new service to handle the routes above inside
src/services
- Update or create new unit tests, integration tests
Using Postman collections for newbie
- Start the server in local (
npm start
) - Open Postman App
- Click
Import
button
- Select the environment file and postman collection file inside
postman-collections
folder - Run the your test/request
- Select a collection
- Choose environment
- Run the first request
- See test case in tab
Tests