chore: moves db adapters to top-level packages

This commit is contained in:
James
2023-07-31 14:26:14 -04:00
parent f69e5949e1
commit 832c1069f1
53 changed files with 2 additions and 3 deletions

View File

@@ -0,0 +1,68 @@
/* eslint-disable @typescript-eslint/no-var-requires */
import type { ConnectOptions } from 'mongoose';
import mongoose from 'mongoose';
import type { MongooseAdapter } from '.';
import type { Connect } from '../../../types';
export const connect: Connect = async function connect(
this: MongooseAdapter,
payload,
) {
if (this.url === false) {
return;
}
if (!payload.local && typeof this.url !== 'string') {
throw new Error('Error: missing MongoDB connection URL.');
}
let urlToConnect = this.url;
let successfulConnectionMessage = 'Connected to MongoDB server successfully!';
const connectionOptions: ConnectOptions & { useFacet: undefined } = {
autoIndex: true,
...this.connectOptions,
useFacet: undefined,
};
if (process.env.NODE_ENV === 'test') {
if (process.env.PAYLOAD_TEST_MONGO_URL) {
urlToConnect = process.env.PAYLOAD_TEST_MONGO_URL;
} else {
connectionOptions.dbName = 'payloadmemory';
const { MongoMemoryServer } = require('mongodb-memory-server');
const getPort = require('get-port');
const port = await getPort();
this.mongoMemoryServer = await MongoMemoryServer.create({
instance: {
dbName: 'payloadmemory',
port,
},
});
urlToConnect = this.mongoMemoryServer.getUri();
successfulConnectionMessage = 'Connected to in-memory MongoDB server successfully!';
}
}
try {
this.connection = (
await mongoose.connect(urlToConnect, connectionOptions)
).connection;
if (process.env.PAYLOAD_DROP_DATABASE === 'true') {
this.payload.logger.info('---- DROPPING DATABASE ----');
await mongoose.connection.dropDatabase();
this.payload.logger.info('---- DROPPED DATABASE ----');
}
this.payload.logger.info(successfulConnectionMessage);
} catch (err) {
this.payload.logger.error(
`Error: cannot connect to MongoDB. Details: ${err.message}`,
err,
);
process.exit(1);
}
};