我按照Apollo Server的指示进行了部署,将其部署为AWS lambda。
https://www.apollographql.com/docs/apollo-server/deployment/lambda/
使用了无服务器框架,并且在East-2区域运行良好。
我将示例扩展为使用PostGres数据库进行查询(我使用了npm sequalize软件包)。当我作为ApolloServer和本地postresql DB运行时,可以使用相同的代码。我这样做是为了也可以切换到apollo-server-lambda。我有一个if语句,它根据是否为lambda来更改与数据库的连接。
我遇到的问题是不会打入数据库的查询工作正常。但是对数据库的graphql查询返回:
{
"error": {
"message": "Internal server error"
}
}
好的,那么现在如何调试nodejs lambda函数?
lambda管理控制台确实具有测试操作。我重新定义了hello world测试以将其用作测试:
{
"operationName": null,"variables": {},"query": "{users {id firstName lastName addressnumber streetName city email createdAt updatedAt }}"
}
但是,这似乎不是调用lambda函数的正确方法。因为日志返回:
{
"body": "Apollo Server supports only GET/POST requests.","statusCode": 405,"headers": {
"Allow": "GET,POST"
}
}
server.js
const { ApolloServer } = require('apollo-server')
const { ApolloServer: ApolloServerLambda } = require('apollo-server-lambda')
const { typeDefs,resolvers,connect } = require('./schema.js')
// The ApolloServer constructor requires two parameters: your schema
// definition and your set of resolvers.
async function setup(server) {
let { url } = await server.listen()
console.log(`? Server ready at ${url}`)
await connect("local")
}
async function awsSetup() {
await connect("aws")
}
if (process.env.username == 'ysg4206') {
const server = new ApolloServer({ typeDefs,resolvers })
setup(server)
} else {
const server = new ApolloServerLambda({ typeDefs,resolvers })
//awsSetup()
exports.graphqlHandler = server.createHandler({
playground: true,introspection: true,cors: {
origin: '*',credentials: true,},context: ({ event,context }) => { return (
{
headers: event.headers,functionName: context.functionName,event,context
})
}
})
}
schema.js
const { gql } = require('apollo-server')
const { DB } = require('./db')
const { GraphQLDateTime } = require('graphql-iso-date')
exports.typeDefs = gql`
scalar DateTime
type User {
id: Int
"English First Name"
firstName: String
lastName: String
addressnumber: Int
streetName: String
city: String
email: String
createdAt: DateTime
updatedAt: DateTime
}
input UserType {
"Hebrew First Name"
firstName: String
lastName: String
addressnumber: Int
streetName: String
city: String
email: String
}
type Query {
users: [User]
findUser(firstName: String): User
hello(reply: String): String
}
type Mutation {
addUser(user: UserType): User!
}
type Subscription {
newUser: User!
}
`
exports.resolvers = {
Query: {
// users: async () => {
// let users = await DB.findAll()
// return users
// },users: () => DB.findAll(),findUser: async (_,{ firstName }) => {
let who = await DB.findFirst(firstName)
return who
},hello: (_,{ reply },context) => {
console.log(`hello with reply ${reply}`)
console.log(`context : ${JSON.stringify(reply,null,4)}`)
return reply
}
},Mutation: {
addUser: async (_,args) => {
let who = await DB.addUser(args.user)
return who
}
}
}
exports.cOnnect= async function connect(where) {
await DB.dbSetup(where)
await DB.populate()
let users = await DB.findAll()
console.log(users)
}
调试lambda函数非常困难!如果通过CloudWatch配置了日志,则可以尝试通过日志进行挖掘,但这并不能总为您提供可行的堆栈跟踪,而且要找到您要查找的确切调用也很困难。
您是否尝试过使用无服务器框架仪表板进行部署?这将帮助您获得完整的堆栈跟踪以及日志。您只需在应用程序根目录中运行serverless
命令即可开始使用。
更多信息可用here
全面披露-我在Serverless Framework上为Serverless Inc.工作。
,
适用于部署无服务器应用程序并在转到其AWS终端节点时收到{"message": "Internal server error"}
的任何人
我整天都在碰这个问题。我做了一些更改,但我认为对我来说,所做的就是在初始化ApolloServer时包括上下文:
const server = new ApolloServer({
...serverConfig,// typeDefs and resolvers
context: ({ event,context }) => ({
headers: event.headers,functionName: context.functionName,event,context,}),playground: {
endpoint: '/dev/graphql',},});
查看此链接:https://www.apollographql.com/docs/apollo-server/deployment/lambda/#getting-request-info
调试时,我建议两件事
- 在AWS上检查您的lambda函数的Cloudwatch日志
- 运行
serverless offline
,转到本地端点,看看是否有任何错误(您需要安装serverless offline plugin并将其包含在serverless.yml
中)
如果您使用的是纱线monorepo和打字稿,则还有一些其他相关信息-
确保编译并翻译打字稿代码。 See this article。我的代码:
-
yarn add webpack serverless-webpack
-
yarn add -D webpack-node-externals
webpack.config.js
const path = require('path');
const slsw = require('serverless-webpack');
const nodeExternals = require('webpack-node-externals');
module.exports = {
entry: slsw.lib.entries,target: 'node',mode: slsw.lib.webpack.isLocal ? 'development' : 'production',optimization: {
minimize: false,performance: {
hints: false,devtool: 'nosources-source-map',externals: [nodeExternals()],module: {
rules: [
{
test: /\.ts$/,loader: 'babel-loader',options: {
presets: [
[
'@babel/preset-env',{
targets: {
node: true,],'@babel/typescript',include: [__dirname],exclude: /node_modules/,resolve: {
extensions: ['.ts','.js'],output: {
libraryTarget: 'commonjs2',path: path.join(__dirname,'.webpack'),filename: '[name].js',};
serverless.yml
# serverless.yml
service: apollo-lambda
plugins:
- serverless-webpack
- serverless-offline
custom:
webpack:
webpackConfig: ./webpack.config.js
includeModules: true
provider:
name: aws
runtime: nodejs12.x
functions:
graphql:
# this is formatted as .
handler: dist/server.graphqlHandler
environment:
SLS_DEBUG: true
events:
- http:
path: graphql
method: post
cors: true
integration: lambda-proxy
- http:
path: graphql
method: get
cors: true
integration: lambda-proxy
tsconfig.json
{
"compilerOptions": {
"sourceMap": true,"outDir": "./dist","strict": true,"lib": ["es5"],"esModuleInterop": true,"types": ["react","jest"]
}
}
我还添加了一个名为deploy
的脚本,该脚本删除了dist
文件夹,并在编译打字稿后重新创建了dist
文件夹(请参阅outDir
中的tsconfig.json
) ,然后运行serverless deploy
:
package.json
{
...
"main": "dist/server.js","scripts": {
...
"deploy": "rimraf dist && npx tsc && serverless deploy",...
}
注意:您需要全局安装rimraf
才能使脚本正常运行(npm install -g rimraf
)