import { MongoClient } from 'mongodb'; const mongodbURL = process.env.MONGO || ''; export const mongoUrlLocal = process.env.MONGO_LOCAL || ''; export const mongoUrlAws = process.env.MONGO_AWS || ''; export async function getMongoClient(url?) { const client = new MongoClient(url || mongodbURL); await client.connect(); return client; } export async function getDb(name) { const client = await getMongoClient(); const db = client.db(name); return { client, db, }; } export async function getGithubCollection(name) { const { db, client } = await getDb('github'); const col = db.collection(name); return { client, col, }; } export const getSinceCol = async () => { const { col, client } = await getGithubCollection('since'); return { col, client, }; }; export async function getCollection(dbName, colName, mongoUrl = '') { const { db, client } = await getDb(dbName); const col = db.collection(colName); return { client, col, }; } export async function getMongoCollection(dbName, colName, mongoUrl = '') { return getCollection(dbName, colName, mongoUrl); } export const createOrUpdateMongoItems = async (col, items, key) => { if (!key) throw new Error('createOrUpdateItems key 不存在'); const updates = items.map((item) => { const { _id, ...otherProps } = item; return otherProps; }).map(item => { const updateMany: any = { filter: { [key]: item[key] }, update: { $set: item }, upsert: true, }; return { updateMany, }; }); const resp = await col.bulkWrite(updates); return resp; }; export async function createIndex({ dbName, colName, mongoUrl, key, sort = 1 }) { const { col, client } = await getCollection(dbName, colName); await col.createIndex([{ [key]: sort, }]); await client.close(); }