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
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# Loopback4
dist
tsconfig.tsbuildinfo

# Serverless
.serverless

Expand Down
76 changes: 8 additions & 68 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,90 +4,30 @@
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/3988cecd1c154bb99c310fb77bbc1ae9)](https://www.codacy.com/app/marcelobern/serverless-loopback?utm_source=github.com&utm_medium=referral&utm_content=botbits/serverless-loopback&utm_campaign=Badge_Grade)
[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fbotbits%2Fserverless-loopback.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fbotbits%2Fserverless-loopback?ref=badge_shield)

A sample [loopback](https://loopback.io/) application deployed to AWS Lambda using [serverless](https://serverless.com/).
A collection of sample [loopback](https://loopback.io/) applications deployed to [AWS Lambda](https://aws.amazon.com/lambda/) using [serverless](https://serverless.com/).

## Overview

A RDS (MySQL) database is created, along with all necessary virtual AWS infrastructure (VPC, subnets, DBSubnetGroup) to connect a lambda function running loopback to the MySQL database. The MySQL connection parameters are retrieved from lambda environment variables.
<!--
For ease of management RDS (MySQL) username/password can be retrieved from [AWS SSM Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-paramstore.html) and used in `serverless.yml` [see section *Handling Secrets for Small Teams & Projects*]](https://serverless.com/blog/serverless-secrets-api-keys/). -->
The following examples are available:

Check out [this article](https://medium.com/smac-4u/serverless-loopback-9ff0d6fa539d) for a more in-depth explanation of this sample.
- [Loopback 3 (using express)](examples/lb3-express/README.md)
- [Loopback 4 (via express)](examples/lb4-express/README.md)

## Using

[Create a *serverless* service](https://serverless.com/framework/docs/providers/aws/cli-reference/create) from this template by using the command:

`serverless create --template-url https://github.com/botbits/serverless-loopback`
`serverless create --template-url https://github.com/botbits/serverless-loopback/examples/<SELECT_EXAMPLE>`

Or clone the git repo:

`git clone https://github.com/botbits/serverless-loopback`

## About Sample Provided
and `cd examples` to start checking your favorite example!

The sample loopback application provided was created by following the process below:
## Contributing

1. Using the command `npm run lb` and selecting:

- What kind of application do you have in mind? `api-server (A LoopBack API server with local User auth)`

2. Adding a new MySQL database to `lib/server/datasources.json`.

3. Adding the CoffeeShop model and initializing it with data:

- `lib/common/coffee-shop.json`: CoffeeShop model definition
- `lib/server/model-config.json`: add CoffeeShop model so it can be loaded
- `lib/server/boot/create-sample-models.js`: initialize CoffeeShop model with data

## Customizing & Deploying This Sample

The following steps can be used to customize this sample to your needs and then deploy:

<!-- 0. (*optional*) For ease of management add MySQL username/password to the AWS SSM Parameter Store (using [AWS Console(https://docs.aws.amazon.com/systems-manager/latest/userguide/param-create-console.html)] or [AWS CLI(https://docs.aws.amazon.com/systems-manager/latest/userguide/param-create-cli.html)]).
-->
1. Create your own loopback models with the command `npm run lb-model`

2. The RDS `mySqlDb` in `serverless.yml` is configured to be as low cost as possible (not suitable for production!) so feel free to [customize it to your needs](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html).

3. Deploy your project to AWS using the command `npm run sls-deploy`

4. From the serverless `Stack Outputs`, retrieve `ServiceEndpoint` (it should look something like `https://API_GATEWAY_ID.execute-api.AWS_REGION.amazonaws.com/SERVERLESS_STAGE`)

5. Access the loopback API explorer by adding `/api/explorer/` to the `ServiceEndpoint` retrieved in the previous step. You should end up with an URL similar to `https://XXXXXXXXXX.execute-api.us-east-1.amazonaws.com/dev/api/explorer/`

*Note*: An error might be observed the first time lambda runs after (re-)creating the RDS database as the CoffeeTable model table might not be initialized before your API is invoked. This error would look something like:

```json
{
"error": {
"statusCode": 500,
"name": "Error",
"message": "ER_NO_SUCH_TABLE: Table 'MY_TEST_DB.CoffeeShop' doesn't exist",
"code": "ER_NO_SUCH_TABLE",
"errno": 1146,
"sqlMessage": "Table 'MY_TEST_DB.CoffeeShop' doesn't exist",
"sqlState": "42S02",
"index": 0,
"sql": "SELECT count(*) as \"cnt\" FROM `CoffeeShop` ",
"stack": "Error: ER_NO_SUCH_TABLE: Table 'MY_TEST_DB.CoffeeShop' doesn't exist\n at ..."
}
}
```

Retry after a few seconds and it all should work.

## Cleaning Up The Sample

Once you are done with the sample environment, avoid unnecessary AWS charges by removing your serverless deployment with the command `npm run sls-cleanup`.

If you run into a cleanup [error similar to the one below](https://forum.serverless.com/t/very-long-delay-when-doing-sls-remove-of-lambda-in-a-vpc/2535), you will need to manually remove the CloudFormation stack by going to: <https://console.aws.amazon.com/cloudformation> or using the [aws-cli](https://aws.amazon.com/cli/).

```shell
Serverless Error ---------------------------------------

An error occurred: mySubnet2 - The subnet 'subnet-077e0f72824fe5dd3' has dependencies and cannot be deleted. (Service: AmazonEC2; Status Code: 400; Error Code: DependencyViolation; Request ID: XXX).
```
Please feel free to contribute your examples of using loopback4 with other web frameworks under the `examples` folder.

## License

Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
78 changes: 78 additions & 0 deletions examples/lb3-express/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# examples/lb3-express

This example shows how to use the [serverless framework](https://www.serverless.com/framework/docs/providers/aws/) to run loopback3 (with express) in [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/lambda-nodejs.html).

## Overview

A RDS (MySQL) database is created, along with all necessary virtual AWS infrastructure (VPC, subnets, DBSubnetGroup) to connect a lambda function running loopback to the MySQL database. The MySQL connection parameters are retrieved from lambda environment variables.
<!--
For ease of management RDS (MySQL) username/password can be retrieved from [AWS SSM Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-paramstore.html) and used in `serverless.yml` [see section *Handling Secrets for Small Teams & Projects*]](https://serverless.com/blog/serverless-secrets-api-keys/). -->

Check out [this article](https://medium.com/smac-4u/serverless-loopback-9ff0d6fa539d) for a more in-depth explanation of this sample.

## About Sample Provided

The sample loopback application provided was created by following the process below:

1. Using the command `npm run lb` and selecting:

- What kind of application do you have in mind? `api-server (A LoopBack API server with local User auth)`

2. Adding a new MySQL database to `lib/server/datasources.json`.

3. Adding the CoffeeShop model and initializing it with data:

- `lib/common/coffee-shop.json`: CoffeeShop model definition
- `lib/server/model-config.json`: add CoffeeShop model so it can be loaded
- `lib/server/boot/create-sample-models.js`: initialize CoffeeShop model with data

## Customizing & Deploying This Sample

The following steps can be used to customize this sample to your needs and then deploy:

<!-- 0. (*optional*) For ease of management add MySQL username/password to the AWS SSM Parameter Store (using [AWS Console(https://docs.aws.amazon.com/systems-manager/latest/userguide/param-create-console.html)] or [AWS CLI(https://docs.aws.amazon.com/systems-manager/latest/userguide/param-create-cli.html)]).
-->
1. Create your own loopback models with the command `npm run lb-model`

2. The RDS `mySqlDb` in `serverless.yml` is configured to be as low cost as possible (not suitable for production!) so feel free to [customize it to your needs](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-rds-database-instance.html).

3. Deploy your project to AWS using the command `npm run sls-deploy`

4. From the serverless `Stack Outputs`, retrieve `LoopbackApiExplorer` to access the loopback4 API explorer (it should look something like `https://API_GATEWAY_ID.execute-api.AWS_REGION.amazonaws.com/SERVERLESS_STAGE/api/explorer/`). You should end up with an URL similar to `https://XXXXXXXXXX.execute-api.us-east-1.amazonaws.com/dev/api/explorer/`.

*Note*: An error might be observed the first time lambda runs after (re-)creating the RDS database as the CoffeeTable model table might not be initialized before your API is invoked. This error would look something like:

```json
{
"error": {
"statusCode": 500,
"name": "Error",
"message": "ER_NO_SUCH_TABLE: Table 'MY_TEST_DB.CoffeeShop' doesn't exist",
"code": "ER_NO_SUCH_TABLE",
"errno": 1146,
"sqlMessage": "Table 'MY_TEST_DB.CoffeeShop' doesn't exist",
"sqlState": "42S02",
"index": 0,
"sql": "SELECT count(*) as \"cnt\" FROM `CoffeeShop` ",
"stack": "Error: ER_NO_SUCH_TABLE: Table 'MY_TEST_DB.CoffeeShop' doesn't exist\n at ..."
}
}
```

Retry after a few seconds and it all should work.

## Cleaning Up The Sample

Once you are done with the sample environment, avoid unnecessary AWS charges by removing your serverless deployment with the command `npm run sls-cleanup`.

If you run into a cleanup [error similar to the one below](https://forum.serverless.com/t/very-long-delay-when-doing-sls-remove-of-lambda-in-a-vpc/2535), you will need to manually remove the CloudFormation stack by going to: <https://console.aws.amazon.com/cloudformation> or using the [aws-cli](https://aws.amazon.com/cli/).

```shell
Serverless Error ---------------------------------------

An error occurred: mySubnet2 - The subnet 'subnet-077e0f72824fe5dd3' has dependencies and cannot be deleted. (Service: AmazonEC2; Status Code: 400; Error Code: DependencyViolation; Request ID: XXX).
```

## License

MIT © [BotBits<sup>SM</sup>](https://github.com/botbits)
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

File renamed without changes.
26 changes: 25 additions & 1 deletion serverless.yml → examples/lb3-express/serverless.yml
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,31 @@ resources:

# The "Outputs" that your AWS CloudFormation Stack should produce. This allows references between services.
Outputs:
RdsDBInstanceIdentifier:
DbInstanceIdentifier:
Description: The DB Name for the (MySQL) RDS created
Value:
Ref: mySqlDb
LoopbackPostman:
Description: The baseUrl value to configure for your Postman collection
Value:
'Fn::Join':
- ''
- - 'https://'
- Ref: 'ApiGatewayRestApi'
- '.execute-api.'
- Ref: 'AWS::Region'
- '.'
- Ref: 'AWS::URLSuffix'
- '/${self:provider.stage}/api'
LoopbackApiExplorer:
Description: The URL to directly access the loopback API explorer
Value:
'Fn::Join':
- ''
- - 'https://'
- Ref: 'ApiGatewayRestApi'
- '.execute-api.'
- Ref: 'AWS::Region'
- '.'
- Ref: 'AWS::URLSuffix'
- '/${self:provider.stage}/api/explorer/'
8 changes: 8 additions & 0 deletions examples/lb4-express/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Copyright IBM Corp. 2020. All Rights Reserved.
// Node module: @loopback/example-express-composition
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT

module.exports = {
extends: ['@loopback/eslint-config'],
};
2 changes: 2 additions & 0 deletions examples/lb4-express/.prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
dist
*.json
7 changes: 7 additions & 0 deletions examples/lb4-express/.prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"bracketSpacing": false,
"singleQuote": true,
"printWidth": 80,
"trailingComma": "all",
"arrowParens": "avoid"
}
20 changes: 20 additions & 0 deletions examples/lb4-express/.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"editor.rulers": [80],
"editor.tabCompletion": "on",
"editor.tabSize": 2,
"editor.trimAutoWhitespace": true,
"editor.formatOnSave": true,

"files.exclude": {
"**/.DS_Store": true,
"**/.git": true,
"**/.hg": true,
"**/.svn": true,
"**/CVS": true,
"dist": true,
},
"files.insertFinalNewline": true,
"files.trimTrailingWhitespace": true,

"typescript.tsdk": "./node_modules/typescript/lib"
}
29 changes: 29 additions & 0 deletions examples/lb4-express/.vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "Watch and Compile Project",
"type": "shell",
"command": "npm",
"args": ["--silent", "run", "build:watch"],
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": "$tsc-watch"
},
{
"label": "Build, Test and Lint",
"type": "shell",
"command": "npm",
"args": ["--silent", "run", "test:dev"],
"group": {
"kind": "test",
"isDefault": true
},
"problemMatcher": ["$tsc", "$eslint-stylish", "$eslint-compact"]
}
]
}
Loading