I am working on a GitHub workflow that updates content in another repo.
workflow:
issues:
types: [opened, reopened]
jobs:
forking:
name: 'Test'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v1
- name: Forking
uses: ./.github/actions/fork
env:
jump2header_token: ${{ secrets.JUMP2HEADER_TOKEN }}
# - name: Sleep for 30 seconds
# uses: jakejarvis/wait-action#master
# with:
# time: '30s'
- name: Update file
uses: ./.github/actions/update_file
env:
jump2header_token: ${{ secrets.JUMP2HEADER_TOKEN } # "x-oauth-scopes": "repo"
import { context, getOctokit } from "#actions/github";
const octokit = getOctokit(process.env.jump2header_token || "");
const response = await octokit.request(
`PUT /repos/{owner}/{repo}/contents/{path}`,
{
owner,
repo,
path: file,
message: generateCommitMessage(),
content,
sha,
branch,
}
);
This is the error that I am getting in the actions workflow:
{
"name": "HttpError",
"status": 404,
"headers": {
"access-control-allow-origin": "*",
"access-control-expose-headers": "ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Used, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type, Deprecation, Sunset",
"connection": "close",
"content-encoding": "gzip",
"content-security-policy": "default-src 'none'",
"content-type": "application/json; charset=utf-8",
"date": "Sun, 13 Dec 2020 18:02:20 GMT",
"referrer-policy": "origin-when-cross-origin, strict-origin-when-cross-origin",
"server": "GitHub.com",
"status": "404 Not Found",
"strict-transport-security": "max-age=31536000; includeSubdomains; preload",
"transfer-encoding": "chunked",
"vary": "Accept-Encoding, Accept, X-Requested-With",
"x-accepted-oauth-scopes": "",
"x-content-type-options": "nosniff",
"x-frame-options": "deny",
"x-github-media-type": "github.v3; format=json",
"x-github-request-id": "0403:379D:747844:12E9DA7:5FD6572B",
"x-oauth-scopes": "repo",
"x-ratelimit-limit": "5000",
"x-ratelimit-remaining": "4994",
"x-ratelimit-reset": "1607885212",
"x-ratelimit-used": "6",
"x-xss-protection": "1; mode=block"
},
"request": {
"method": "PUT",
"url": "https://api.github.com/repos/strdr4605/TMPS/contents/README.md",
"headers": {
"accept": "application/vnd.github.v3+json",
"user-agent": "octokit-core.js/3.2.4 Node.js/12.13.1 (linux; x64)",
"authorization": "token [REDACTED]",
"content-type": "application/json; charset=utf-8"
},
"body": "{\"message\":\"docs: add links to top with jump2header\",\"content\":\"IyBUTVBTCg==\",\"sha\":\"e734b6a1805da1b08294715d5ede2761fd4807e5\",\"branch\":\"jump2header\"}",
...
}
Why 404 error if the repo exists: https://api.github.com/repos/strdr4605/TMPS/contents/README.md?
Am I doing the update right?
A 404 generally means an authentication issue: for security reason, the API pretends there is no such resource (even if it exists) when it detects you are not allowed to access/update it.
The action-update-file action should require a GitHub token for authentication
Example:
name: Resources
on: repository_dispatch
jobs:
resources:
name: Update resources
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v1
- uses: actions/setup-node#v1
- name: Fetch resources
run: ./scripts/fetch-resources.sh
- name: Update resources
uses: test-room-7/action-update-file#v1
with:
file-path: path/to/file
commit-msg: Update resources
github-token: ${{ secrets.GITHUB_TOKEN }}
Related
I am taking over an AWS lambda serverless nodejs app and I am trying to figure out how to execute an endpoint in my development environment. For my purposes I am trying to simulate a request like the following:
http://localhost:3000/find/product?hiveProductId=22002233&zipCode=44035
the app includes the following in handler.js
app.route("/find/product").get(cors(), async (req, res) => {
try {
console.log(
"finding product",
req.query
);
etc...
} catch (error) {
console.error("caught error finding product: ", error);
res.status(500).json(error);
}
});
module.exports.find = serverless(app);
There is also the following in serverless.yml:
functions:
find:
handler: handler.find
events:
- http:
path: /find/product
method: GET
memorySize: 128
timeout: 30
private: false
cors: true
integration: lambda-proxy
request:
parameters:
querystrings:
hiveProductId: true
max: false
lat: false
lon: false
allowGeoIp: false
zipCode: false
methodReponses:
- statusCode: "200"
responseBody:
description: "array of stores with product"
responseModels:
"application/json": "Stores"
- statusCode: "404"
description: "not found"
- http:
path: /find/stores
method: GET
memorySize: 128
timeout: 30
integration: lambda-proxy
private: true
request:
parameters:
querystrings:
max: false
lat: true
lon: true
documentation:
summary: "Find the closest stores"
queryParams:
- name: "lat"
description: "latitude caller for geosearch"
required: true
- name: "lon"
description: "longtitude caller for geosearch"
required: true
- name: "max"
description: "maximum stores to location to return. default is 5"
methodReponses:
- statusCode: "200"
responseBody:
description: "array of stores sorted by distance"
responseModels:
"application/json": "Stores"
I have been using https://www.serverless.com/framework/docs/providers/aws/cli-reference/invoke-local/ for a reference. serverless invoke local seems like what I'm looking for. serverless invoke local --function find gives the following response:
{
"statusCode": 404,
"headers": {
"x-powered-by": "Express",
"content-security-policy": "default-src 'none'",
"x-content-type-options": "nosniff",
"content-type": "text/html; charset=utf-8",
"content-length": "139"
},
"isBase64Encoded": false,
"body": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Cannot GET /</pre>\n</body>\n</html>\n"
}
Any advice or pointers on how to use serverless invoke correctly, or a different approach to look into, or any documentation that would be more fruitful, would be greatly appreciated.
I haven't used this method before, so I can't say anything. I can recommend serverless-offline as a different solution. serverless-offline
You are asking how to test and debug serverless apps..
Here is the .vscode/launch.json(placed in root directory of VS Code project) I am using for it(I am using VS code always):
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Lambda",
"runtimeExecutable": "/Users/ninjablade/.nvm/versions/node/v12.18.0/bin/node",
"cwd": "${workspaceFolder}/lambda-mock",
"program": "/usr/local/bin/sls",
"args": [
"invoke",
"local",
"-f",
"resolvers",
"-p",
"../mocks/resolvers.json"
],
"skipFiles": ["<node_internals>/**"]
},
]
}
As you can notice here, we are running $ sls invoke local -f function -p data command (you can check out exact guide for this command from sls framework documentation)
As a -p option of this command, we can pass any info we need for the endpoint. You can get the test event data from Cloud Watch log easily and replace it with your test input data.
$ sls invoke local command will simulate the exactly same lambda environment in your local development environment and let you test your lambda function in your local.
This post will help your a lot Debug Serverless app by VS Code.
Thanks
I have written a small function that requests data from a "hidden" API. It is a simple GET request and it works flawlessly when I run locally, but I receive a 403 Forbidden response when I try to deploy to Heroku. The strange thing is it worked several days ago no issue.
address = https://a810-dobnow.nyc.gov/Publish/PublicPortalWrapper/WrapperService.svc/getPublicPortalPropertyDetailsGet/1%7C318%7CWEST%2088%20STREET%7C1
fetch(address, {
headers: {
accept:
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"accept-language": "en-US,en;q=0.9",
"cache-control": "max-age=0",
"sec-fetch-dest": "document",
"sec-fetch-mode": "navigate",
"sec-fetch-site": "none",
"sec-fetch-user": "?1",
"upgrade-insecure-requests": "1"
// cookie:
// "_ga=GA1.2.1003098932.1594177672; _abck=C3A49F4C33DC14B4AEC19A7EBC5ACB7A~0~YAAQiUMkF2ogZFZzAQAAsvKfZwQfXDkq7euJF0D2hRXAI2V1AruFzXLsOUSc59t7XNzo9iAXH5X1hH0WZkHU2/jyyCcQZO7iOKhK5SV68dIBzVnbK87jIJGLiP5SnbL5Vc9cb+jStzQUpnjOLG59Z1YwYX8pBBNF1xCmUE9p5JJGHt2eA/1A+szh3Fsd7Pa1Y/gNqCYlaMeG9KobxAhWrxPGSI8UqfJEY24rP53Sjkk2RnVQtOm4Ndym5VctS0E078oS7rO2ErVUciCd7KIm6uTqAIZaLCThpn38Lvv7Bw==~-1~-1~-1; WT_FPC=id=f89669c2-f54a-4a08-8417-488c541da028:lv=1595295049155:ss=1595295008235; ASP.NET_SessionId=fvhtl1mq5byqybp0vn4rvkk0; _gid=GA1.2.778374792.1596222780; bm_mi=8303530FA5B983C6A2C37AD6A50F1AB0~DwWIcg/T4TLuW4ckdSijBe3wsAObA+OJOKRuvmdxP64cGhS6O67EOei1JDxamYFX6tF8BcezG1nFQK8QcvDTvBA2ZwT0CifQcO7VSg9cAcLoYATKRjs0vahwRFMGb3hpm826BjjMbcMrdU0GW0U1JQxqNbtc5kFZBM3022kwyv0VGDzY3NNW7BWZHqToNvx2z6qHKJgnDb1V0TeZ/AjuFP89BX784OrYSTkaiSZLbg6BnM3HmCXznFFf0+IaMhxU2MgqrGwoITehpPQfuzZ2HGx1hhfWZ0xa0MGKZnZhd0w=; ak_bmsc=728816F52039F5DD770B7D4B6536D20717408D2C753F0000316D245FB7EF451C~plc8JV/GDGNtsmUQ/jrI8X7yLHGcKff9dnWlC62FcsMQEB3ENDDfKz8e1f/edVvmGAOdiXJdHstFeuQG18Sg95iSqHA8xYy6vqPUNz2DcmRmIK4ZqgsMgXgQ7SLSvxOxFTfsIkV83XG87pDK8HpYh6oO1sI33FGj5ZsRe2y8o88+cY/xI1CAuqtQNZbHf3SzhfkP0tzqeLtUoHuH8nZPyIluF4LxGSI9WhTndADPDMap+F9gPOm12ubgZRwcgJPKyl; NSC_mc_qfstjtuhspvq_dppljf=ffffffff9eb452ce45525d5f4f58455e445a4a42378b; bm_sv=CFE4F539604441CC66374C6DBD92BDD0~7PQFpr8AaDw9KWD30agg7TrTgydB1GbhFszaf7zAlHQJaWLcaclQ66BxK2PBdF3XoSvzzvutMQWGxTWg+TRgOudrUF1Gu8yUwwIv0IMv7imBGm1deHPcQCoDo3JsMZud2DJsOC35QEV60c4j8CuPjQ=="
},
referrer: "https://a810-dobnow.nyc.gov/publish/",
referrerPolicy: "no-referrer-when-downgrade",
body: null,
method: "GET",
mode: "cors"
})
I have deployed serverless function with an API integreated. Below is the code
Serverless.yml
service: serverless-rest-api-with-dynamodb
provider:
name: aws
runtime: python3.8
region: eu-west-1
environment:
DYNAMODB_TABLE: ${self:service}-${opt:stage, self:provider.stage}
iamRoleStatements:
- Effect: Allow
Action:
- dynamodb:Query
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
Resource: "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_TABLE}"
logs: true
functions:
myFunc:
handler: handler.customer
events:
- http:
path: customer_details
method: post
resources:
Resources:
TodosDynamoDbTable:
Type: 'AWS::DynamoDB::Table'
DeletionPolicy: Retain
Properties:
TableName: CustomerTablev1
AttributeDefinitions:
- AttributeName: id
AttributeType: S
- AttributeName: CustomerName
AttributeType: S
KeySchema:
-
AttributeName: id
KeyType: HASH
- AttributeName: CustomerName
KeyType: RANGE
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
handler.py
import json
def customer(event, context):
postData= event['body']
return {
'statusCode': 200,
'body': "Hello Post accepted",
"content-type": "application/json"
}
Below is the permission i have added for the api to invoke the lambda function
{
"Policy": "{\"Version\":\"2012-10-17\",\"Id\":\"default\",\"Statement\":
[{\"Sid\":\"serverless-rest-api-with-dynamodb-dev-MyFuncLambdaPermissionApiGateway-dfdd22\",
\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"apigateway.amazonaws.com\"},
\"Action\":\"lambda:InvokeFunction\",
\"Resource\":\"arn:aws:lambda:eu-west-1:##3d64543:function:serverless-rest-api-with-dynamodb-dev-myFunc\",
\"Condition\":{\"ArnLike\":{\"AWS:SourceArn\":\"arn:aws:execute-api:eu-west-1:##343d64543:tmx8paevk3/*/*\"}}},
{\"Sid\":\"###23232dfecfb\",
\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"apigateway.amazonaws.com\"},
\"Action\":\"lambda:InvokeFunction\",
\"Resource\":\"arn:aws:lambda:eu-west-1:##3d64543:function:serverless-rest-api-with-dynamodb-dev-myFunc\",
\"Condition\":{\"ArnLike\":{\"AWS:SourceArn\":\"arn:aws:execute-api:eu-west-1:##3d64543:tmx8paevk3/*/POST/customer_details\"}}},
{\"Sid\":\"apigateway\",\"Effect\":\"Allow\",\"Principal\":{\"Service\":\"apigateway.amazonaws.com\"},
\"Action\":\"lambda:InvokeFunction\",\"Resource\":\"arn:aws:lambda:eu-west-1:##3d64543:function:serverless-rest-api-with-dynamodb-dev-myFunc\"}]}",
"RevisionId": "##3d64543ddf-4ecdfe"
}
I called api with the body request, for eg:
{
"Name":"123"
}
Below is the log
Verifying Usage Plan for request: 33434-df-sdf##. API Key: API Stage: tmx8paevk3/dev
API Key authorized because method 'POST /customer_details' does not require API Key. Request will not contribute to throttle or quota limits
Usage Plan check succeeded for API Key and API Stage tmx8paevk3/dev
Starting execution for request: 343-f-er-###
HTTP Method: POST, Resource Path: /customer_details
Method request path:
{}
(c3434-ffg34--sd2qw) Method request query string:
{}
Method request headers: {Accept=application/json, CloudFront-Viewer-Country=IN, CloudFront-Forwarded-Proto=https, CloudFront-Is-Tablet-Viewer=false, CloudFront-Is-Mobile-Viewer=false, User-Agent=Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36, X-Forwarded-Proto=https, CloudFront-Is-SmartTV-Viewer=false, Host=tmx8paevk3.execute-api.eu-west-1.amazonaws.com, Accept-Encoding=gzip, deflate, X-Forwarded-Port=443, X-Amzn-Trace-Id=Root=1-5e08179b-231fd1c4058eaaa020eff0d0, Via=1.1 da86ace2d9b441802dcc77e25582499b.cloudfront.net (CloudFront), X-Amz-Cf-Id=oXgrxNvE97x-3FvOB7_85BawEcIIGe5Puzy6S9XIiKSDj8yLZQv-Ig==, X-Forwarded-For=117.204.125.144, 52.46.37.72, content-type=application/json, Accept-Language=en-US,en;q=0.8, CloudFront-Is-Desktop-Viewer=true}
Method request body before transformations:
{
"name": "test"
}
Endpoint request URI: https://lambda.eu-west-1.amazonaws.com/2013-233-32/functions/arn:aws:lambda:eu-west-1:3d##:function:serverless-rest-api-with-dynamodb-dev-myFunc/invocations
Endpoint request headers: {x-amzn-lambda-integration-tag=##sdsd-sd23, Authorization=************************************************************************************************************************************************************************************************************************************************************************************************************************d9c3f1, X-Amz-Date=20191229T030355Z, x-amzn-apigateway-api-id=tmx8paevk3, X-Amz-Source-Arn=arn:aws:execute-api:eu-west-1:7###343434:tmx8paevk3/dev/POST/customer_details, Accept=application/json, User-Agent=AmazonAPIGateway_tm##we, X-Amz-Security-Token=I###12323/D######/xfP2323######//////////8B#######/334####/dsd## [TRUNCATED]
Endpoint request body after transformations:
{
"name": "test"
}
Sending request to https://lambda.eu-west-1.amazonaws.com/2015-03-31/functions/arn:aws:lambda:eu-west-1:####:function:serverless-rest-api-with-dynamodb-dev-myFunc/invocations
Received response. Status: 200, Integration latency: 263 ms
Endpoint response headers: {Date=Sun, 29 Dec 2019 03:03:56 GMT, Content-Type=application/json, Content-Length=86, Connection=keep-alive, x-amzn-RequestId=3443D-23#, x-amzn-Remapped-Content-Length=0, X-Amz-Executed-Version=$LATEST, X-Amzn-Trace-Id=23d=-dere###;sampled=0}
Endpoint response body before transformations:
{
"statusCode": 200,
"body": "Hello Post accepted",
"content-type": "application/json"
}
Execution failed due to configuration error: Output mapping refers to an invalid method response: 200
Method completed with status: 500
AWS Integration Endpoint RequestId : 323d-fer-vsd###
But still it returns 500 internal error. I searched different ways to get the solution, and everybody says its only due to the lack of permission that API must have to invoke the lambda. As i already provided the permission to the API, i want to know what exactly, what would be the solution for this?
Appreciate if anyone can help on this?
I have reviewed and tested your Serverless Framework code and after slight modification I was able to get the setup working by making the following changes :
handler.py
import json
def hello(event, context):
postData = event['body']
# Prepare a response dictionary as required by API Gateway
response = {
"statusCode": 200,
"isBase64Encoded": False,
"headers": {},
"content-type": "application/json",
"body": json.dumps(postData)
}
return response
Serverless.yml
service: HelloWorld
provider:
name: aws
runtime: python2.7
region: eu-west-1
iamRoleStatements:
- Effect: Allow
Action:
- dynamodb:Query
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
Resource: "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_TABLE}"
logs: true
environment:
DYNAMODB_TABLE: '${self:service}-${opt:stage, self:provider.stage}'
functions:
hello:
handler: handler.hello
events:
- http:
path: customers-details
method: POST
integration: LAMBDA # Add this line
resources:
Resources:
TodosDynamoDbTable:
Type: 'AWS::DynamoDB::Table'
DeletionPolicy: Retain
Properties:
TableName: CustomerTablev1
AttributeDefinitions:
- AttributeName: id
AttributeType: S
- AttributeName: CustomerName
AttributeType: S
KeySchema:
-
AttributeName: id
KeyType: HASH
- AttributeName: CustomerName
KeyType: RANGE
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
Curl Test
Request:
curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"name":"syumaK"}' --url https://z0uu17yp6f.execute-api.eu-west-1.amazonaws.com/dev/customers-details
Response:
{"body": "{\"name\": \"syumaK\"}", "headers": {}, "content-type": "application/json", "isBase64Encoded": false, "statusCode": 200}%
The takeaway point is that when working with Serverless Framework and AWS Lambda(Lambda proxy) you have to add to the following line in your serverless.yml under events:
integration: LAMBDA
Hope this helps!
You response body is the problem here:
{
'statusCode': 200,
'body': "Hello Post accepted",
"content-type": "application/json"
}
It should be something be(as you are setting header as json and passing normal text):
{
'statusCode': 200,
'body': json.dumps({"reply":"Hello Post accepted"}),
"content-type": "application/json"
}
I'd like to run a function via both HTTP and cron, but not seeing any documentation that let's me determine if it was an http request or cron request (explicitly):
events:
- http:
path: /foo
method: ANY
cors:
origin: '*'
- schedule: rate(5 minute)
Is there a property in event or context that would allow me to detect what triggered the function?
You can always pass an input to your schedule event and use that to determine that's a schedule event
events:
- http:
path: /foo
method: ANY
cors:
origin: '*'
- schedule:
rate: rate(5 minute)
input:
isSchedule: true
There's more examples here: https://serverless.com/framework/docs/providers/aws/events/schedule/
EDIT:
Forgot about this
{
"version": "0",
"id": "53dc4d37-cffa-4f76-80c9-8b7d4a4d2eaa",
"detail-type": "Scheduled Event",
"source": "aws.events",
"account": "123456789012",
"time": "2015-10-08T16:53:06Z",
"region": "us-east-1",
"resources": [
"arn:aws:events:us-east-1:123456789012:rule/my-scheduled-rule"
],
"detail": {}
}
you can also check detail-type field
https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/RunLambdaSchedule.html
Need help with this error -
{
"errorMessage": "RequestId: 18120028-124f-11e9-9e46-b3db6ae39b34 Process exited before completing request"
}
Also, I have the following in the logs
2019-01-07T07:37:32.797Z 18120028-124f-11e9-9e46-b3db6ae39b34 UnexpectedParameter: Unexpected key 'BillingMode' found in params
at ParamValidator.fail (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:50:37)
at ParamValidator.validateStructure (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:77:14)
at ParamValidator.validateMember (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:88:21)
at ParamValidator.validate (/var/runtime/node_modules/aws-sdk/lib/param_validator.js:34:10)
at Request.VALIDATE_PARAMETERS (/var/runtime/node_modules/aws-sdk/lib/event_listeners.js:125:42)
at Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:105:20)
at callNextListener (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:95:12)
at /var/runtime/node_modules/aws-sdk/lib/event_listeners.js:85:9
at finish (/var/runtime/node_modules/aws-sdk/lib/config.js:320:7)
at /var/runtime/node_modules/aws-sdk/lib/config.js:338:9
Here is my package.json
{
"name": "xxxxxxx",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"aws-sdk": "^2.382.0",
"serverless-dynamodb-local": "^0.2.35",
"uuid": "^3.3.2"
},
"devDependencies": {
"bcrypt-nodejs": "0.0.3",
"dynamoose": "^1.3.0",
"factory-girl": "^5.0.4",
"faker": "^4.1.0",
"moment": "^2.23.0",
"serverless-aws-documentation": "^1.1.0",
"serverless-mocha-plugin": "^1.9.1",
"serverless-offline": "^3.31.3",
"serverless-plugin-include-dependencies": "^3.2.1",
"serverless-reqvalidator-plugin": "^1.0.3",
"serverless-webpack": "^5.2.0",
"webpack": "^4.27.1"
}
}
Here is the action -
'use strict';
const Insider = require('../models/insider').Insider;
const InsiderTest = require('../models/insider').InsiderTest;
module.exports.index = (_event, _context, callback) => {
const klass = (process.env.STAGE == 'test') ? InsiderTest : Insider
klass.scan().exec((_err, data) => {
if (data.count == 0) {
callback(null, {
statusCode: 422,
error: 'No Insiders'
});
return;
}
const response = {
data: {
results: data
},
statusCode: 200
}
callback(null, response);
});
};
serverless.yml
service: vs-aws-lambda-serverless-services
package:
exclude:
- node_modules/**
include:
- models/**
plugins:
- serverless-reqvalidator-plugin
- serverless-aws-documentation
- serverless-offline
- serverless-dynamodb-local
- serverless-mocha-plugin
- serverless-plugin-include-dependencies
#############################################
# Standard Serverless Definition
#############################################
provider:
name: aws
region: xxxxxxx
runtime: nodejs8.10
stage: xxxx
iamRoleStatements:
- Effect: Allow
Action:
- dynamoDB:DescribeTable
- dynamoDB:Query
- dynamoDB:Scan
- dynamoDB:GetItem
- dynamoDB:PutItem
- dynamoDB:UpdateItem
- dynamoDB:DeleteItem
Resource: "arn:aws:dynamodb:xxxxxxx:*:*"
#############################################
# #############################################
# # Model Definitions - API Gateway
# #############################################
custom:
documentation:
models:
-
name: CreateSuccessResponse
contentType: 'application/json'
schema:
type: object
properties:
message:
type: string
statusCode:
type: string
-
name: xxxxxxsRequest
contentType: 'application/json'
schema:
type: object
required:
- name
properties:
name:
type: string
profileImage:
type: string
gender:
type: string
fullDescription:
type: string
shortDescription:
type: string
interests:
type: array
personalities:
type: array
travelledCities:
type: array
tribes:
type: array
funFacts:
type: array
dynamodb:
start:
migrate: true
#############################################
#############################################
# Lambda Functions
#############################################
functions:
listInsiders:
handler: insiders/index.index
events:
- http:
path: insiders
method: get
cors: true
integration: lambda
response:
headers:
Access-Control-Allow-Origin: "'*'"
documentation:
methodResponses:
-
statusCode: '200'
responseModels:
"application/json": CreateSuccessResponse
#############################################
#############################################
# Resource Definitions
#############################################
resources:
Resources:
xxxxxxsDynamoDBTable:
Type: AWS::DynamoDB::Table
Properties:
AttributeDefinitions:
-
AttributeName: uuid
AttributeType: S
KeySchema:
-
AttributeName: uuid
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
TableName: 'table_name'
requestBody:
Type: 'AWS::ApiGateway::RequestValidator'
Properties:
Name: 'requestBody'
RestApiId:
Ref: ApiGatewayRestApi
ValidateRequestBody: true
#############################################