mongodb#Db TypeScript Examples

The following examples show how to use mongodb#Db. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: zoneserver.ts    From h1z1-server with GNU General Public License v3.0 6 votes vote down vote up
async onCharacterCreateRequest(client: any, packet: any) {
    const { characterObjStringify, reqId } = packet.data;
    try {
      const characterObj = JSON.parse(characterObjStringify);
      const collection = (this._db as Db).collection("characters");
      const charactersArray = await collection.findOne({
        characterId: characterObj.characterId,
      });
      if (!charactersArray) {
        await collection.insertOne(characterObj);
      }
      this._h1emuZoneServer.sendData(client, "CharacterCreateReply", {
        reqId: reqId,
        status: 1,
      });
    } catch (error) {
      this._h1emuZoneServer.sendData(client, "CharacterCreateReply", {
        reqId: reqId,
        status: 0,
      });
    }
  }
Example #2
Source File: db.ts    From filecoin-CID-checker with Apache License 2.0 6 votes vote down vote up
export function getDbo(): Promise<Db> {
  if (dbo) return Promise.resolve(dbo)

  prettyLogger.info(
    { uri: DB_CONNECTION.uri, name: DB_CONNECTION.options.dbName },
    `${NS} Initializing DB connection...`,
  )

  return new Promise((resolve, reject) => {
    MongoClient.connect(
      DB_CONNECTION.uri,
      {
        ...DB_CONNECTION.options,
      },
      function (err, db) {
        if (err) {
          prettyLogger.error(err, `${NS} watcher DB connector error`)
          return reject(err)
        }
        dbo = db.db(DB_CONNECTION.options.dbName)

        prettyLogger.info(`${NS} DB connected`)

        return resolve(dbo)
      },
    )
  })
}
Example #3
Source File: db.ts    From o7 with MIT License 6 votes vote down vote up
// Usage guides:
// https://docs.mongodb.com/drivers/node/usage-examples/findOne
// https://docs.mongodb.com/drivers/node/usage-examples/find
// https://docs.mongodb.com/drivers/node/usage-examples/insertOne
// https://docs.mongodb.com/drivers/node/usage-examples/insertMany
// https://docs.mongodb.com/drivers/node/usage-examples/updateOne
// https://docs.mongodb.com/drivers/node/usage-examples/updateMany
// https://docs.mongodb.com/drivers/node/usage-examples/replaceOne
// https://docs.mongodb.com/drivers/node/usage-examples/deleteOne
// https://docs.mongodb.com/drivers/node/usage-examples/deleteMany
export function getClient(): MongoClient & { getDb: () => Db; } {
  const client = <any>new MongoClient(config.mongo.connectionString, { useNewUrlParser: true, useUnifiedTopology: true });
  client.getDb = () => client.db(config.mongo.database);
  return client;
}
Example #4
Source File: mongo.ts    From peterportal-client with MIT License 6 votes vote down vote up
/**
 * Get a mongo database object
 * @returns Mongo database object
 */
function getDB(): Promise<Db> {
    return new Promise((resolve, reject) => {
        // if not connected yet, initiate connection
        if (!db) {
            client.connect(async err => {
                if (err) {
                    reject(err);
                }
                else {
                    db = client.db(DB_NAME);

                    // get existing mongo collection
                    let collectionNames = Object.values(COLLECTION_NAMES);
                    let collections = await db.listCollections().toArray();
                    let existingCollectionNames: string[] = [];
                    collections.forEach(collection => {
                        existingCollectionNames.push(collection['name']);
                    })

                    // create collections that dont exist
                    for (let i = 0; i < collectionNames.length; ++i) {
                        let collectionName = collectionNames[i];
                        if (!existingCollectionNames.includes(collectionName)) {
                            await db.createCollection(collectionName);
                        }
                    }
                    resolve(db);
                }
            });
        }
        else {
            resolve(db);
        }
    })
}
Example #5
Source File: roll-forward.ts    From metroline with GNU General Public License v3.0 6 votes vote down vote up
export async function rollForward(db: Db, client: MongoClient): Promise<void> {
  logger.debug('Rolling forward');
  const migrated: any[] = await up(db, client);
  if (migrated?.length > 0) {
    migrated.forEach(fileName => logger.info(`Migrated ${chalk.bold(fileName)}`));
  } else {
    logger.info('Nothing to migrate');
  }
}
Example #6
Source File: roll-forward.spec.ts    From metroline with GNU General Public License v3.0 6 votes vote down vote up
describe('rollforward', () => {
  let db: Db;
  let client: MongoClient;

  beforeEach(() => {
    db = {} as any;
    client = {} as any;
  });

  afterEach(() => {
    jest.clearAllMocks();
    jest.restoreAllMocks();
  });

  it('should run migration', async () => {
    await rollForward(db, client);

    expect(up).toHaveBeenCalledWith(db, client);
  });
});
Example #7
Source File: roll-backwards.ts    From metroline with GNU General Public License v3.0 6 votes vote down vote up
export async function rollBackwards(db: Db, client: MongoClient): Promise<void> {
  logger.debug('Rolling back');
  const migratedDown = await down(db, client);
  if (migratedDown?.length > 0) {
    migratedDown.forEach(fileName => logger.info(`Rolled back migration: ${chalk.bold(fileName)}`));
  } else {
    logger.info('No migration to roll back');
  }
}
Example #8
Source File: roll-backwards.spec.ts    From metroline with GNU General Public License v3.0 6 votes vote down vote up
describe('rollBackwards', () => {
  let db: Db;
  let client: MongoClient;

  beforeEach(() => {
    db = {} as any;
    client = {} as any;
  });

  afterEach(() => {
    jest.clearAllMocks();
    jest.restoreAllMocks();
  });

  it('should run migration', async () => {
    await rollBackwards(db, client);
    expect(down).toHaveBeenCalledWith(db, client);
  });
});
Example #9
Source File: migrate.ts    From metroline with GNU General Public License v3.0 6 votes vote down vote up
// https://github.com/seppevs/migrate-mongo#api-usage
export async function migrate(client: MongoClient, db: Db): Promise<void> {
  if (env.METROLINE_MIGRATE_ROLLBACK) {
    await rollBackwards(db, client);
    logger.debug('Exiting after rollback');
    process.exit(0);
  } else {
    await rollForward(db, client);
  }
}
Example #10
Source File: Db.ts    From vircadia-metaverse with Apache License 2.0 5 votes vote down vote up
Datab: Db
Example #11
Source File: Database.ts    From discord-statuspage-v2 with MIT License 5 votes vote down vote up
public db: Db
Example #12
Source File: db.ts    From filecoin-CID-checker with Apache License 2.0 5 votes vote down vote up
dbo: Db
Example #13
Source File: db.ts    From monkeytype with GNU General Public License v3.0 5 votes vote down vote up
getDb = (): Db | undefined => db
Example #14
Source File: db.ts    From monkeytype with GNU General Public License v3.0 5 votes vote down vote up
db: Db
Example #15
Source File: setup-tests.ts    From monkeytype with GNU General Public License v3.0 5 votes vote down vote up
jest.mock("./src/init/db", () => ({
  __esModule: true,
  getDb: (): Db => db,
  collection: <T>(name: string): Collection<WithId<T>> =>
    db.collection<WithId<T>>(name),
}));
Example #16
Source File: setup-tests.ts    From monkeytype with GNU General Public License v3.0 5 votes vote down vote up
db: Db
Example #17
Source File: migrate.spec.ts    From metroline with GNU General Public License v3.0 5 votes vote down vote up
describe('migrate', () => {
  let db: Db;
  let client: MongoClient;

  let rollForward: SpyInstance;
  let rollbackwards: SpyInstance;
  let processExit: SpyInstance;

  beforeEach(() => {
    db = {} as any;
    client = { close: jest.fn().mockReturnValue(Promise.resolve()) } as any;

    rollForward = jest.spyOn(_rollup, 'rollForward').mockReturnValue(Promise.resolve());
    rollbackwards = jest.spyOn(_rollback, 'rollBackwards').mockReturnValue(Promise.resolve());
    processExit = jest.spyOn(process, 'exit').mockImplementation((() => undefined) as any);
  });

  afterEach(() => {
    jest.clearAllMocks();
    jest.restoreAllMocks();
    delete env.METROLINE_MIGRATE_ROLLBACK;
  });

  it('should rollForward', async () => {
    await migrate(client, db);

    expect(rollForward).toHaveBeenCalledWith(db, client);
    expect(rollbackwards).not.toHaveBeenCalled();
  });

  it('should rollBackwards and exit when rollback enabled', async () => {
    env.METROLINE_MIGRATE_ROLLBACK = true;

    await migrate(client, db);

    expect(rollbackwards).toHaveBeenCalledWith(db, client);
    expect(processExit).toHaveBeenCalledWith(0);
    expect(rollForward).not.toHaveBeenCalled();
  });
});
Example #18
Source File: configure-indexes.ts    From metroline with GNU General Public License v3.0 5 votes vote down vote up
async function createCollectionIfNotExists(name: string, db: Db): Promise<Collection> {
  const collections = await db.collections();
  const collection = collections.find(col => col.collectionName === name);
  return collection || db.createCollection(name);
}
Example #19
Source File: configure-indexes.spec.ts    From metroline with GNU General Public License v3.0 5 votes vote down vote up
describe('configure-indexes', () => {
  afterEach(() => {
    jest.clearAllMocks();
    jest.restoreAllMocks();
    jest.resetModules();
  });

  describe('configureIndexes', () => {
    let db: Db;
    let client: MongoClient;
    let configureIndexesForCollection: SpyInstance;

    beforeEach(() => {
      db = {
        collections: jest.fn(),
        collection: jest.fn(),
        createCollection: jest.fn(),
      } as any;
      client = { db: jest.fn().mockReturnValue(db) } as Partial<MongoClient> as any;

      configureIndexesForCollection = jest.spyOn(_configureIndexesForCollection, 'configureIndexesForCollection').mockReturnValue(Promise.resolve());
    });

    it('should create registered indexes', async () => {
      const indexes = {
        collection1: [
          { fieldOrSpec: 'test1' },
        ],
        collection2: [
          { fieldOrSpec: 'test2' },
        ],
      };

      jest.spyOn(db, 'collections').mockImplementation(() => Promise.resolve([
        { collectionName: 'collection1' },
        { collectionName: 'collection2' },
      ]));

      await configureIndexes(client, indexes);

      expect(configureIndexesForCollection.mock.calls).toEqual([
        [{ collectionName: 'collection1' }, [
          { fieldOrSpec: 'test1' },
        ]],
        [{ collectionName: 'collection2' }, [
          { fieldOrSpec: 'test2' },
        ]],
      ]);
    });

    it('should create collection when it does not exist', async () => {
      jest.spyOn(db, 'collections').mockImplementation(() => Promise.resolve(['collection1']));
      const createCollection = jest.spyOn(db, 'createCollection').mockImplementation(() => Promise.resolve('collection1'));

      const indexes = {
        collection1: [
          { fieldOrSpec: 'test1' },
        ],
      };

      await configureIndexes(client, indexes);

      expect(createCollection).toHaveBeenCalledWith('collection1');
      expect(configureIndexesForCollection.mock.calls).toEqual([
        ['collection1', [
          { fieldOrSpec: 'test1' },
        ]],
      ]);
    });
  });
});
Example #20
Source File: db.ts    From metroline with GNU General Public License v3.0 5 votes vote down vote up
static db: Db;
Example #21
Source File: database.ts    From shorty with MIT License 5 votes vote down vote up
db: Db
Example #22
Source File: index.ts    From integration-services with Apache License 2.0 5 votes vote down vote up
public static db: Db;
Example #23
Source File: mongo.ts    From peterportal-client with MIT License 5 votes vote down vote up
db: Db = undefined!
Example #24
Source File: db.server.ts    From master-frontend-lemoncode with MIT License 5 votes vote down vote up
getDBInstance = (): Db => dbInstance
Example #25
Source File: db.server.ts    From master-frontend-lemoncode with MIT License 5 votes vote down vote up
dbInstance: Db
Example #26
Source File: zoneserver.ts    From h1z1-server with GNU General Public License v3.0 5 votes vote down vote up
_db: Db | undefined;
Example #27
Source File: zoneserver.ts    From h1z1-server with GNU General Public License v3.0 4 votes vote down vote up
constructor(
    serverPort: number,
    gatewayKey: Uint8Array,
    mongoAddress = "",
    worldId = 0,
    internalServerPort = 1118
  ) {
    super();
    this._gatewayServer = new GatewayServer(
      "ExternalGatewayApi_3",
      serverPort,
      gatewayKey
    );
    this._mongoAddress = mongoAddress;
    this._worldId = worldId;
    this._protocol = new ZoneProtocol();
    this._clients = {};
    this._characters = {};
    this._npcs = {};
    this._objects = {};
    this._doors = {};
    this._vehicles = {};
    this._props = {};
    this._destroyablesTimeout = {};
    this._speedTrees = {};
    this._destroyables = {};
    this._serverTime = this.getCurrentTime();
    this._transientIds = {};
    this._packetHandlers = new zonePacketHandlers();
    this._startTime = 0;
    this._time = Date.now();
    this._startGameTime = 0;
    this._timeMultiplier = 72;
    this._cycleSpeed = 0;
    this._soloMode = false;
    this._defaultWeatherTemplate = "h1emubaseweather";
    this._profiles = [];
    this._items = [];
    this._interactionDistance = 4;
    this._npcRenderDistance = 350;
    this._pingTimeoutTime = 120000;
    this._dynamicWeatherEnabled = true;
    this._dummySelf = require("../../../data/2015/sampleData/sendself.json");
    this._appDataFolder = getAppDataFolderPath();
    if (!this._mongoAddress) {
      this._soloMode = true;
      debug("Server in solo mode !");
    }
    this.on("data", this.onZoneDataEvent);

    this.on("login", (err, client) => {
      this.onZoneLoginEvent(err, client);
    });

    this._gatewayServer._soeServer.on("fatalError", (soeClient: SOEClient) => {
      const client = this._clients[soeClient.sessionId];
      this.deleteClient(client);
      // TODO: force crash the client
    });

    this._gatewayServer.on(
      "login",
      (
        err: string,
        client: SOEClient,
        characterId: string,
        loginSessionId: string,
        clientProtocol: string
      ) => {
        this.onGatewayLoginEvent(
          err,
          client,
          characterId,
          loginSessionId,
          clientProtocol
        );
      }
    );

    this._gatewayServer.on("disconnect", (err: string, client: Client) => {
      this.onGatewayDisconnectEvent(err, client);
    });

    this._gatewayServer.on(
      "tunneldata",
      (err: string, client: Client, data: Buffer, flags: number) => {
        this.onGatewayTunnelDataEvent(
          err,
          this._clients[client.sessionId],
          data,
          flags
        );
      }
    );

    if (!this._soloMode) {
      this._h1emuZoneServer = new H1emuZoneServer(internalServerPort); // opens local socket to connect to loginserver

      this._h1emuZoneServer.on(
        "session",
        (err: string, client: H1emuClient) => {
          if (err) {
            debug(
              `An error occured for LoginConnection with ${client.sessionId}`
            );
            console.error(err);
          } else {
            debug(`LoginConnection established for ${client.sessionId}`);
          }
        }
      );

      this._h1emuZoneServer.on(
        "sessionfailed",
        (err: string, client: H1emuClient) => {
          console.error(`h1emuServer sessionfailed for ${client.sessionId}`);
          console.error(err);
          process.exit(1);
        }
      );

      this._h1emuZoneServer.on(
        "disconnect",
        (err: string, client: H1emuClient, reason: number) => {
          debug(
            `LoginConnection dropped: ${
              reason ? "Connection Lost" : "Unknown Error"
            }`
          );
        }
      );

      this._h1emuZoneServer.on(
        "data",
        async (err: string, client: H1emuClient, packet: any) => {
          if (err) {
            console.error(err);
          } else {
            switch (packet.name) {
              case "CharacterCreateRequest": {
                this.onCharacterCreateRequest(client, packet);
                break;
              }
              case "CharacterExistRequest": {
                const { characterId, reqId } = packet.data;
                try {
                  const collection = (this._db as Db).collection("characters");
                  const charactersArray = await collection
                    .find({ characterId: characterId })
                    .toArray();
                  if (charactersArray.length) {
                    this._h1emuZoneServer.sendData(
                      client,
                      "CharacterExistReply",
                      { status: 1, reqId: reqId }
                    );
                  } else {
                    this._h1emuZoneServer.sendData(
                      client,
                      "CharacterExistReply",
                      { status: 0, reqId: reqId }
                    );
                  }
                } catch (error) {
                  this._h1emuZoneServer.sendData(
                    client,
                    "CharacterExistReply",
                    { status: 0, reqId: reqId }
                  );
                }
                break;
              }
              case "CharacterDeleteRequest": {
                const { characterId, reqId } = packet.data;
                try {
                  const collection = (this._db as Db).collection("characters");
                  const charactersArray = await collection
                    .find({ characterId: characterId })
                    .toArray();
                  if (charactersArray.length === 1) {
                    await collection.updateOne(
                      { characterId: characterId },
                      {
                        $set: {
                          status: 0,
                        },
                      }
                    );
                    this._h1emuZoneServer.sendData(
                      client,
                      "CharacterDeleteReply",
                      { status: 1, reqId: reqId }
                    );
                  } else {
                    this._h1emuZoneServer.sendData(
                      client,
                      "CharacterDeleteReply",
                      { status: 1, reqId: reqId }
                    );
                  }
                } catch (error) {
                  this._h1emuZoneServer.sendData(
                    client,
                    "CharacterDeleteReply",
                    { status: 0, reqId: reqId }
                  );
                }
                break;
              }
              default:
                debug(`Unhandled h1emu packet: ${packet.name}`);
                break;
            }
          }
        }
      );
    }
  }