Nuxt3のserverで、AWSのDocumentDBに接続するのに手間取ったので、私の環境でうまく行った方法を公開します。
仕様
以下のようにローカルでは、MongoDBに接続し、AWSではDocumentDBに接続する。
ローカル:Docker, MongoDB, Nuxt3
AWS:ECS Fargate, DocumentDB, Nuxt3
コード
server/database.ts
import mongoose from 'mongoose';
import fs from 'fs';
import path from 'path';
const connection: {
isConnected: any;
db: mongoose.Connection | undefined;
} = {
isConnected: false,
db: undefined,
};
async function connectDB() {
if (connection.isConnected) {
return connection.db;
}
let db = undefined;
console.log('connecting');
const username = encodeURIComponent(process.env.MONGODB_USERNAME || '');
const password = encodeURIComponent(process.env.MONGODB_PASSWORD || '');
const host = process.env.MONGODB_HOST;
if (process.env.IS_DEV) {
db = await mongoose.connect(`mongodb://${host}/`, {
"authSource": "admin",
"user": username,
"pass": password,
});
} else {
const caBundlePath = path.resolve(process.cwd(), './public/rds-combined-ca-bundle.pem');
try {
db = await mongoose.connect(`mongodb://${username}:${password}@${host}/`, {
tls: true,
sslValidate: true,
tlsCAFile: caBundlePath,
replicaSet: 'rs0',
readPreference: 'secondaryPreferred',
retryWrites: false,
});
console.log('MongoDB Connected');
} catch (err) {
console.log('MongoDB Connection Error: ', err);
}
}
if (!db) return;
console.log('connected');
connection.isConnected = db.connections[0].readyState;
connection.db = db.connections[0].useDb('YOUR_DB_NAME');
return connection.db;
}
export default connectDB;
pemファイル設置
DocumentDBは、TLSで認証しているので、その対応をする。
publicディレクトリに rds-combined-ca-bundle.pem
を設置する。
ダウンロード方法は以下の通り。
$ wget https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem
最後に
TLS認証でめちゃくちゃ時間かかった。。。