hardyscc / aws-nestjs-starter Goto Github PK
View Code? Open in Web Editor NEWServerless, AWS, NestJS, GraphQL and DynamoDB starter
License: The Unlicense
Serverless, AWS, NestJS, GraphQL and DynamoDB starter
License: The Unlicense
Hi, I use this snippet and i want support websocket gateway.
I already configure my serverless.yml. when i request my socket endpoint I receive the data of my request in the variable event, but it does not forward it to my gateway.
How resolve this?
import { NestFactory } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';
import { APIGatewayProxyHandler } from 'aws-lambda';
import { createServer, proxy } from 'aws-serverless-express';
import { eventContext } from 'aws-serverless-express/middleware';
import express from 'express';
import { Server } from 'http';
import { AppModule } from './app.module';
let cachedServer: Server;
const bootstrapServer = async (): Promise<Server> => {
const expressApp = express();
expressApp.use(eventContext());
const app = await NestFactory.create(
AppModule,
new ExpressAdapter(expressApp),
);
app.useGlobalPipes(new ValidationPipe({ forbidUnknownValues: true }));
app.enableCors();
await app.init();
return createServer(expressApp);
};
export const handler: APIGatewayProxyHandler = async (event, context) => {
if (!cachedServer) {
cachedServer = await bootstrapServer();
}
console.log('---event', event);
// console.log('---context', context);
return proxy(cachedServer, event, context, 'PROMISE').promise;
};
More than an issue is a question ๐ฌ . The official docs says that using webpack decrease the cold start time, because the bundle that is maded. Why dont you use it on this starter project?, is there a reason not to use it? ๐ค .
Besides that, thanks for the effort ๐ช
I wanted to try this template but noticed that it still uses dynamoose, which doesn't fully support Typescript and is somewhat limited in that area. Having in mind that this repo is almost fully written in TS I would propose a change to some other package such as:
There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.
Location: renovate.json
Error type: The renovate configuration file contains some invalid settings
Message: matchUpdateTypes: matchUpdateTypes should be inside a 'packageRule' only
This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.
These branches will be created by Renovate only once you click their checkbox below.
These updates are awaiting their schedule. Click on a checkbox to get an update now.
These updates await pending status checks. To force their creation now, click the checkbox below.
@typescript-eslint/eslint-plugin
, @typescript-eslint/parser
)These updates have all been created already. Click a checkbox below to force a retry/rebase of any.
.github/workflows/nodejs.yml
actions/checkout v4
actions/setup-node v4
actions/upload-artifact v4
actions/checkout v4
actions/download-artifact v4
SonarSource/sonarcloud-github-action v2.1.1
package.json
@apollo/server 4.10.4
@graphql-tools/merge 9.0.3
@nestjs/apollo 12.1.0
@nestjs/common 10.3.8
@nestjs/config 3.2.2
@nestjs/core 10.3.8
@nestjs/graphql 12.1.1
@nestjs/platform-express 10.3.8
@vendia/serverless-express 4.12.6
class-transformer 0.5.1
class-validator 0.14.1
dynamoose 4.0.1
graphql 16.8.1
husky 9.0.11
nestjs-dynamoose 0.5.8
reflect-metadata 0.2.2
rimraf 5.0.5
rxjs 7.8.1
uuid 9.0.1
@commitlint/cli 19.3.0
@commitlint/config-conventional 19.2.2
@nestjs/cli 10.3.2
@nestjs/schematics 10.1.1
@nestjs/testing 10.3.8
@shelf/jest-dynamodb 3.4.4
@trivago/prettier-plugin-sort-imports 4.3.0
@types/aws-lambda 8.10.137
@types/express 4.17.21
@types/jest 29.5.12
@types/js-yaml 4.0.9
@types/node 20.12.7
@types/serverless 3.12.22
@types/supertest 6.0.2
@types/uuid 9.0.8
@typescript-eslint/eslint-plugin 7.7.1
@typescript-eslint/parser 7.7.1
change-case 5.4.4
cross-env 7.0.3
eslint 8.57.0
eslint-config-prettier 9.1.0
eslint-plugin-import 2.29.1
glob-promise 6.0.5
jest 29.7.0
js-yaml 4.1.0
lint-staged 15.2.2
prettier 3.2.5
serverless 3.38.0
serverless-dynamodb-local 0.2.40
serverless-offline 13.4.0
serverless-plugin-typescript 2.1.5
supertest 6.3.4
ts-jest 29.1.2
ts-loader 9.5.1
ts-node 10.9.2
tsconfig-paths 4.2.0
typescript 5.4.5
Hi! I worked with your source base. But if i set prefix stg-tableName
DynamoDb created a new table with a prefix. It worked
But the transaction function got an error. All class use transaction or transaction Support got error
Table \"stg-points\" not found. Please register the table with dynamoose before using it in transactions.
@Module({
imports: [
ConfigModule.forRoot({ envFilePath: '.env' }),
DynamooseModule.forRoot({
logger: false,
aws: {
region: process.env.AWS_REGION,
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
},
table: {
create: true,
waitForActive: true,
initialize: true,
update: false,
tableClass: TableClass.infrequentAccess,
prefix:
process.env.NODE_ENV !== 'dev' ? `${process.env.NODE_ENV}-` : '',
},
}),
],
providers: [transactionBase, DynamooseModule],
exports: [transactionBase],
})
export class DynamodbModule {}
My schema
export const LotteryModel: Required<ModelDefinition> = {
name: ETableName.LOTTERIES,
schema: new Schema(
{
userId: {
type: String,
hashKey: true,
},
title: {
type: String,
},
quantity: {
type: Number,
},
},
{
timestamps: defaultSettings,
},
),
options: {
tableName: ETableName.LOTTERIES,
},
serializers: {},
};
my module
@Module({
imports: [
DynamooseModule.forFeature([LotteryModel, RewardModel]),
DynamodbModule,
UserModule,
PointModule,
],
controllers: [LotteryController],
providers: [LotteryService, LotteryRepo, RewardRepo],
})
export class LotteryModule {}
I have two lambda (separate project) developed in nestjs + grapqh. I am trying to call one of the lambda through the other and get responses with the invoke function of aws sdk.
Did the problem come from my way of writing the payload? because I have tried several formats but still no result.
because I noticed that the request is well received by the second lambda, but it may not be able to resolve it.
Tks in advance for your feedback
let lambda = new Lambda({
apiVersion: '2015-03-31',
endpoint: process.env.IS_DDB_LOCAL === 'true'
? 'http://localhost:3002'
: 'https://lambda.us-east-1.amazonaws.com',
});
const params = {
FunctionName: 'FunctionName', eg: demo-dev-index-function
InvocationType: 'RequestResponse',
// Payload: JSON.stringify({ data: 'foo' }),
Payload: JSON.stringify({
query: `{
findIdentityWithPhoneNumber(phoneNumber: "99999999") {
ObjectId
uuid
}
}`
}),
}
const response = await lambda.invoke(params).promise()
console.log(response);
{
StatusCode: 200,
Payload: '{"statusCode":404,"body":"{\\"statusCode\\":404,\\"message\\":\\"Cannot GET /\\",\\"error\\":\\"Not Found\\"}","headers":{"x-powered-by":"Express","access-control-allow-origin":"*","content-type":"application/json; charset=utf-8","content-length":"63","etag":"W/\\"3f-GR0G8sZfNVmVbqqGkyrPOefU7Ys\\"","date":"Wed, 28 Apr 2021 10:05:40 GMT","connection":"close"},"isBase64Encoded":false}'
}
//serverless.yml for the called function
service: serviceName
useDotenv: true
provider:
lambdaHashingVersion: 20201221
name: aws
runtime: nodejs12.x
memorySize: 256
stage: ${opt:stage, 'dev'}
region: ${opt:region}
environment:
SERVICE: ${self:service}
STAGE: ${self:provider.stage}
REGION: ${self:provider.region}
VERSION: ${env:VERSION}
LOCALE: ${env:LOCALE}
apiGateway:
shouldStartNameWithService: true
iam:
role:
statements:
-
Effect: "Allow"
Action:
- "lambda:InvokeFunction"
Resource: "*"
-
Effect: Allow
Action:
- dynamodb:DescribeTable
- dynamodb:Query
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
Resource: arn:aws:dynamodb:${self:provider.region}:*:*
plugins:
- serverless-plugin-typescript
- serverless-dynamodb-local
- serverless-offline
# remove the unnecessary packages to keep small upload size
package:
patterns:
- '!node_modules/typescript/**'
- '!node_modules/@types/**'
custom:
dynamodb:
stages:
- ${self:provider.stage}
start:
port: 8000
inMemory: true
migrate: true
seed: false
functions:
index-function:
handler: src/index.handler
events:
- http:
cors: true
path: '{proxy+}'
method: any
resources:
- ${file(resource/dynamodb.yml)}
I have been using DynamoDB for a long time and use the custom query param LastEvaluatedKey to get the next records list.
however, I can't find that one or a similar query in your source code.
Could you please tell me where is that?
Everything was fine until I started importing services from other modules, I'm looking for a reference to this error, the error occurs when you run it with lambda, but everything is fine with nest js
`service: sales-api-dev
plugins:
provider:
name: aws
apiGateway:
restApiId: hiden
restApiRootResourceId: hiden
iamRoleStatements:
- Effect: Allow
Action:
- dynamodb:DescribeTable
- dynamodb:Query
- dynamodb:Scan
- dynamodb:GetItem
- dynamodb:PutItem
- dynamodb:UpdateItem
- dynamodb:DeleteItem
Resource: arn:aws:dynamodb:${self:provider.region}::
runtime: nodejs14.x
stage: ${opt:stage, 'dev'}
region: us-east-2
package:
exclude:
- .gitignore
- README.md
- serverless.yml
- nest-cli.json
- .prettierrc
excludeDevDependencies: true
individually: true
functions:
main:
handler: src/main.handler
events:
- http:
cors: true
path: '{proxy+}'
method: any
custom:
stages:
- dev
- test
- acc
- prod
serverless-offline:
useChildProcesses: true
`
Any help in this regard would be very helpful, I clarify that it only happens with serverless
version: '3'
services:
dynamodb:
image: amazon/dynamodb-local
hostname: dynamodb-local
container_name: dynamodb-local
ports:
- "8000:8000"
command: ["-jar", "DynamoDBLocal.jar", "-sharedDb", "-inMemory"]
proposed changes:
npm uninstall @types/aws-serverless-express
npm uninstall aws-serverless-express
npm i --save @vendia/serverless-express
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';
import serverlessExpress from '@vendia/serverless-express';
import { APIGatewayProxyHandler, Handler } from 'aws-lambda';
import express from 'express';
import { AppModule } from './app.module';
let cachedServer: Handler;
const bootstrapServer = async (): Promise<Handler> => {
const expressApp = express();
const app = await NestFactory.create(AppModule, new ExpressAdapter(expressApp));
app.useGlobalPipes(new ValidationPipe({ forbidUnknownValues: true }));
app.enableCors();
await app.init();
return serverlessExpress({
app: expressApp
});
};
export const handler: APIGatewayProxyHandler = async (event, context, callback) => {
if (!cachedServer) {
cachedServer = await bootstrapServer();
}
return cachedServer(event, context, callback);
};
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.