簡體   English   中英

無服務器框架+ AWS + Lambda + DynamoDB + GraphQL + Apollo服務器=無法使POST請求生效

[英]Serverless framework + AWS + Lambda + DynamoDB + GraphQL + Apollo Server = Can't make POST Request Work

好的,幾天以來我一直在解決這個問題。

我嘗試學習本教程: https : //serverless.com/blog/make-serverless-graphql-api-using-lambda-dynamodb/

並使其與apollo-server-lambda一起使用。 本教程幫助:

https://medium.com/vessels/apollo-server-serverless-graphql-bliss-68e8e15195ac

問題是,當您嘗試將apollo服務器lambda與DynamoDB進行真正的連接時,對我來說,什么都不起作用。 我得到了一個我已經不記得的錯誤列表了,這只是令人沮喪。

這是我的代碼:

# serverless.yml
service: graphql-api

provider:
  name: aws
  runtime: nodejs6.10
  region: eu-west-3
  stage: dev
  environment:
    DYNAMODB_TABLE: ${self:service}-${self:provider.stage}
  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:GetItem
        - dynamodb:UpdateItem
      Resource: "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_TABLE}"

resources:
  Resources:
    NicknamesTable:
      Type: 'AWS::DynamoDB::Table'
      Properties:
        AttributeDefinitions:
          - AttributeName: firstName
            AttributeType: S
        KeySchema:
          - AttributeName: firstName
            KeyType: HASH
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
        TableName: ${self:provider.environment.DYNAMODB_TABLE}

functions:
  graphql:
    handler: handler.graphql
    events:
      - http:
          path: graphql
          method: post
          cors: true
      - http:
          path: graphql
          method: get
          cors: true

而我的經理:

# handler.js
const AWS = require('aws-sdk');
const server = require("apollo-server-lambda");
const makeExecutableSchema = require('graphql-tools').makeExecutableSchema;
const dynamoDb = new AWS.DynamoDB.DocumentClient();

const promisify = foo => new Promise((resolve, reject) => {
    foo((error, result) => {
        if (error) {
            reject(error)
        } else {
            resolve(result)
        }
    })
})

const getGreeting = firstName => promisify(callback =>
    dynamoDb.get({
        TableName: process.env.DYNAMODB_TABLE,
        Key: { firstName },
    }, callback))
    .then(result => {
        if (!result.Item) {
            return firstName
        }
        return result.Item.nickname
    })
    .then(name => `Hello, ${name}.`)

// add method for updates
const changeNickname = (firstName, nickname) => promisify(callback =>
    dynamoDb.update({
        TableName: process.env.DYNAMODB_TABLE,
        Key: { firstName },
        UpdateExpression: 'SET nickname = :nickname',
        ExpressionAttributeValues: {
            ':nickname': nickname
        }
    }, callback))
    .then(() => nickname)

const typeDefs = `
    type Query {
        greeting(firstName: String!): String
    }
    type Mutation {
        changeNickname(
            firstName: String!
            nickname: String!
        ): String
    }
`;

const resolvers = {
    Query: {
        greeting: (_, { firstName }) => getGreeting(firstName),
    },
    Mutation: {
        changeNickname: (_, { firstName, nickname }) => changeNickname(firstName, nickname),
    }
};

exports.graphql = function (event, context, callback) {
    const callbackFilter = function (error, output) {
        output.headers = output.header || {};
        output.headers['Access-Control-Allow-Origin'] = '*';
        callback(error, output);
    };
    const handler = server.graphqlLambda({ schema: makeExecutableSchema({ typeDefs, resolvers }) });

    return handler(event, context, callbackFilter);
};

我嘗試使用Apollo 1和2,沒有任何作用。 我回到了版本1,因為有更多關於它的論壇帖子。 通常,我有“內部服務器錯誤”。 我嘗試了在apollo文檔中找到的不同版本的服務器,但是所有請求都失敗了,在終端上或直接在AWS的API網關上進行curl測試功能。 我根據此文檔編寫了請求正文: https : //www.apollographql.com/docs/apollo-server/requests.html

這是我的cloudwatch日志:

(node:1) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): SyntaxError: Unexpected token = in JSON at position 8

任何幫助將不勝感激!

好的,我知道了問題所在。 使用put函數時,無法獲得僅插入dynamoDB中的新項。 您必須將“ ReturnValues:'ALL_OLD'”放入params對象(put函數的第一個參數)中,就像不會引發任何錯誤一樣,由於您剛剛在數據庫中輸入了值,因此您應該返回所需的值。

此處有更多詳細信息:

https://github.com/aws/aws-sdk-js/issues/803

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM