typescript 无法访问Amazon DynamoDB

rnmwe5a2  于 12个月前  发布在  TypeScript
关注(0)|答案(2)|浏览(111)

大家好。我在这里请求帮助在Node.js + Typescript后端配置Amazon DynamoDB。我正在尝试创建一个记录到dynamoDB数据库。我使用Node.js + Express作为后端,当我尝试访问DynamoDB时遇到此错误

Error: Resolved credential object is not valid
    at SignatureV4.validateResolvedCredentials (D:\morgan (2)\React + Node.js\DWQ\server\node_modules\.pnpm\@[email protected]\node_modules\@smithy\signature-v4\dist-cjs\SignatureV4.js:182:19)   
    at SignatureV4.signRequest (D:\morgan (2)\React + Node.js\DWQ\server\node_modules\.pnpm\@[email protected]\node_modules\@smithy\signature-v4\dist-cjs\SignatureV4.js:107:14) {
  '$metadata': { attempts: 1, totalRetryDelay: 0 }
}

字符串
这是我的代码。

// dbconfig.ts

import { DynamoDBClient } from "@aws-sdk/client-dynamodb";

// Create Amazon DynamoDB service client object
const ddbClient: DynamoDBClient = new DynamoDBClient({
  region: process.env.REGION,
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
  },
});

export { ddbClient };

x

// ddbDocClient.ts

import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";
import { ddbClient } from "./dbconfig";

const marshallOptions = {
  convertEmptyValues: false, // Whether to automatically convert empty strings, blobs, and sets to `null`
  removeUndefinedValues: true, // Whether to remove undefined values while marshalling
  convertClassInstanceToMap: false, // Whether to convert typeof object to map attribute.
};

const unmarshallOptions = {
  wrapNumbers: false, // Whether to return numbers as a string instead of converting them to native JavaScript numbers.
};

// Create the DynamoDB document client.
const ddbDocClient = DynamoDBDocumentClient.from(ddbClient, {
  marshallOptions,
  unmarshallOptions,
});

export { ddbDocClient };
// UserController.ts

static async register(req: Request, res: Response) {
    const parsedData: RegisterUserInput = RegisterUserSchema.parse(req.body);
    const { confirm, creditNumber, expireMonth, expireYear, creditCode, creditZip, creditOwner, ...filteredInput } = parsedData;
    const hashedPassword: string = await bcrypt.hash(filteredInput.password, 12);

    // Query command finds user by email
    const queryParams: QueryCommandInput = {
        TableName: "users",
        KeyConditionExpression: "email = :email",
        ExpressionAttributeValues: {
            ":email": filteredInput.email,
        },
    };

    // Create a new user data
    const putParams: PutCommandInput = {
        TableName: "users",
        Item: {
            _id: uuidv4(),
            ...filteredInput,
            password: hashedPassword
        }
    };

    await ddbDocClient.send(new QueryCommand(queryParams))
        .then(existUser => {
            // If the user email exists in the database
            if (existUser.Items && existUser.Items.length > 0) {
                res.status(200).json({
                    success: false,
                    message: "User email already exists.",
                });
            } else {
                // Create a new user if it doesn't exist
                // const data = await ddbDocClient.send(new PutCommand(putParams));

                res.status(201).json({
                    success: true,
                    message: "Successfully registered!",
                    result: data,
                });
             }
        })
        .catch(error => {
            console.log(error);

            // Return error response from the server
            res.status(500).json({
                success: false,
                message: "Internal Server Error",
                error
            });
        });
}

的字符串
我可以确定我已经正确地设置了env变量。请帮助我。

pprl5pva

pprl5pva1#

首先,我强烈建议您不要直接将凭据编码到客户端,您应该从角色中解析它们。
但是,您看到的异常是因为您传递了错误的值作为凭据。

tf7tbtn2

tf7tbtn22#

我自己解决的,是因为我收到空的env变量,我设置了dotenv config,成功得到了。

import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import * as dotenv from 'dotenv';

dotenv.config();

// Create Amazon DynamoDB service client object
const ddbClient: DynamoDBClient = new DynamoDBClient({
  region: process.env.REGION,
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
  },
});

export { ddbClient };

字符串

相关问题