mongodb#ObjectId TypeScript Examples

The following examples show how to use mongodb#ObjectId. 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: message-subscriptions.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
@Subscription(returns => Message, {
    topics: CONSTANTS.NEW_MESSAGE,
    filter: filterRoom,
  })
  onNewMessage(
    @Root() message: Message,
    @Arg("roomId") roomId: ObjectID
  ): Message {
    return message;
  }
Example #2
Source File: RestApi.ts    From majsoul-api with MIT License 6 votes vote down vote up
private getSessions(contest: store.Contest<ObjectId>): Observable<Session> {
		return concat(
			defer(() => from(
				this.mongoStore.sessionsCollection.find(
					{ contestId: contest._id },
					{ sort: { scheduledTime: 1 } }
				).toArray()
			)).pipe(
				mergeAll(),
			),
			of<store.Session<ObjectId>>(null)
		).pipe(
			pairwise(),
			map(([session, nextSession]) =>
				defer(() => from(this.getSessionSummary(contest, session, nextSession)))
					.pipe(
						map(totals => {
							return { ...session, totals, aggregateTotals: totals };
						})
					)
			),
			mergeAll(),
		);
	}
Example #3
Source File: urls.ts    From Uptimo with MIT License 6 votes vote down vote up
async function handler(
    req: NextApiRequest,
    res: NextApiResponse
) {
    const session = await getSession({ req });

    if (!session) {
        res.status(403).json({
            message: 'You must log in before getting the urls.',
        })

        return;
    }

    const collection = (await clientPromise).db('Uptimo').collection('users');
    const account = await (await collection.findOne({ _id: new ObjectId(session?.user.id) }));

    res.status(200).json({
        message: account?.urls
    })

    res.end();
}
Example #4
Source File: FakeNotificationsRepository.ts    From gobarber-api with MIT License 6 votes vote down vote up
public async create({
    recipient_id,
    content,
  }: ICreateNotificationDTO): Promise<Notification> {
    const notification = new Notification();

    Object.assign(notification, { id: new ObjectID(), recipient_id, content });

    this.notifications.push(notification);

    return notification;
  }
Example #5
Source File: RestApi.ts    From majsoul-api with MIT License 6 votes vote down vote up
private findContest(contestId: string, options?: FindOneOptions): Promise<store.Contest<ObjectId>> {
		return this.mongoStore.contestCollection.findOne(
			{
				$or: [
					{ majsoulFriendlyId: parseInt(contestId) },
					{ _id: ObjectId.isValid(contestId) ? ObjectId.createFromHexString(contestId) : null },
				]
			},
			options ?? {
				projection: {
					'teams.image': false,
					sessions: false,
				}
			}
		);
	}
Example #6
Source File: FakeNotificationsRepository.ts    From hotseat-api with MIT License 6 votes vote down vote up
public async create({
    content,
    recipient_id,
  }: ICreateNotificationDTO): Promise<Notification> {
    const notification = Object.assign(new Notification(), {
      id: new ObjectID(),
      content,
      recipient_id,
    });

    this.notifications.push(notification);

    return notification;
  }
Example #7
Source File: connector.ts    From majsoul-api with MIT License 6 votes vote down vote up
function createContestIds$(mongoStore: store.Store): Observable<ObjectId> {
	return merge(
		mongoStore.ContestChanges.pipe(
			filter(changeEvent => changeEvent.operationType === "insert"),
			map((changeEvent: ChangeEventCR<store.Contest<ObjectId>>) => changeEvent.documentKey._id)
		),
		defer(() => from(mongoStore.contestCollection.find().toArray()))
			.pipe(
				mergeAll(),
				map(contest => contest._id)
			)
	);
}
Example #8
Source File: UpdateNotificationReadStatusService.ts    From hotseat-api with MIT License 6 votes vote down vote up
public async execute(id: ObjectID): Promise<Notification | undefined> {
    const notification = this.notificationsRepository.findById(id);

    if (!notification) {
      throw new AppError('Notification not found', 404);
    }

    const updatedNotification = await this.notificationsRepository.updateReadStatus(
      id,
    );

    if (!updatedNotification) {
      throw new AppError('Notification not found', 404);
    }

    return updatedNotification;
  }
Example #9
Source File: AlertService.ts    From ethgaswatch with MIT License 6 votes vote down vote up
export async function UpdateMultipleUserAlerts(addresses: RegisteredEmailAddress[], fields: any): Promise<boolean> { 

    try { 
        const collection = await getDatabaseCollection();
        const ids = addresses.map(i => new ObjectId(i._id));
        const result = await collection.updateMany(
            { _id : { $in: ids } },
            { $set: fields });
        
        console.log("Update results", addresses.length === result.modifiedCount, addresses.length, result.modifiedCount)
        return result.modifiedCount > 0;
    } 
    catch (ex) { 
        console.log("ERROR updating user alert", ex);
    }

    return false;
}
Example #10
Source File: survey-result-mongo-repository.ts    From clean-ts-api with GNU General Public License v3.0 6 votes vote down vote up
async save (data: SaveSurveyResultRepository.Params): Promise<void> {
    const surveyResultCollection = MongoHelper.getCollection('surveyResults')
    await surveyResultCollection.findOneAndUpdate({
      surveyId: new ObjectId(data.surveyId),
      accountId: new ObjectId(data.accountId)
    }, {
      $set: {
        answer: data.answer,
        date: data.date
      }
    }, {
      upsert: true
    })
  }
Example #11
Source File: create-schema.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
createSchema = () => {
  return buildSchema({
    resolvers: [
      RoomResolver,
      UserResolver,
      MessageResolver,
      InvitationResolver,
      NotificationResolver,
      MessageSubscriptions,
      NotificationsSubscriptions,
    ],
    globalMiddlewares: [TypegooseMiddleware],
    scalarsMap: [{ type: ObjectID, scalar: ObjectIdScalar }],
    authChecker: useAuth,
  });
}
Example #12
Source File: createCaptcha.spec.ts    From tezos-academy with MIT License 6 votes vote down vote up
describe('User', () => {
  beforeAll(async () => {
    process.env.FROM_EMAIL = '[email protected]'
    await mockConnect()
  })

  it('registration can get captcha', async (done) => {
    const userId = new ObjectId('5e678dc6929100d88de390e2')
    const captchaFor: CaptchaFor = CaptchaFor.CAPTCHA_FOR_VERIFY_EMAIL
    const captchaIndex = 0
    const captchaSolution: CaptchaSolution = '0000'

    jest.spyOn(getRandomCaptchaPairObject, 'getRandomCaptchaPair').mockReturnValue({ captchaIndex, captchaSolution })

    const captcha: Captcha = await createCaptcha(userId, captchaFor)

    expect(captcha).toBeDefined()
    expect(captcha.solution).toBe(captchaSolution)
    expect(captcha.index).toBe(captchaIndex)
    expect(captcha.userId).toBe(userId)
    expect(dayjs(captcha.expiresAt).unix()).toBeLessThanOrEqual(dayjs(captcha.createdAt).unix() + 3600)
    expect(dayjs(captcha.expiresAt).unix()).toBeGreaterThanOrEqual(dayjs(captcha.createdAt).unix() + 3000)

    expect(getRandomCaptchaPairObject.getRandomCaptchaPair).toHaveBeenCalled()

    done()
  })

  afterAll(async () => {
    jest.clearAllMocks()
    const userId = 'testUserId'
    const captchaFor: CaptchaFor = CaptchaFor.CAPTCHA_FOR_VERIFY_EMAIL
    await CaptchaModel.deleteOne({ userId, captchaFor })
  })
})
Example #13
Source File: logger.ts    From monkeytype with GNU General Public License v3.0 6 votes vote down vote up
logToDb = async (
  event: string,
  message: any,
  uid?: string
): Promise<void> => {
  const logsCollection = db.collection<Log>("logs");

  logger.info(`${event}\t${uid}\t${JSON.stringify(message)}`);
  logsCollection.insertOne({
    _id: new ObjectId(),
    timestamp: Date.now(),
    uid: uid ?? "",
    event,
    message,
  });
}
Example #14
Source File: invitation-resolver.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
@Authorized()
  @Mutation(() => InvitationLinkResult)
  async createInvitationLink(
    @Arg("roomId", { nullable: false }) roomId: ObjectID,
    @Ctx() context: Context
  ) {
    const existingInvitation = await InvitationModel.findOne({
      roomId: roomId,
      invitedBy: context.currentUser.id,
      isPublic: true,
    });

    const baseURL =
      process.env.NODE_ENV !== "production"
        ? "http://localhost:3000"
        : "https://convoychat.herokuapp.com";

    if (existingInvitation) {
      return {
        link: `${baseURL}/invitation/${existingInvitation.token}`,
      };
    }

    const validRoom = await RoomModel.findOne({ _id: roomId });
    if (!validRoom) throw new Error("Not a valid room");

    // TODO: add expiry time in invitation token
    const token = crypto.randomBytes(16).toString("hex");
    const invite = new InvitationModel({
      isPublic: true,
      roomId: roomId,
      invitedBy: context.currentUser.id,
      token: token,
    });

    await invite.save();

    return { link: `${baseURL}/invitation/${token}` };
  }
Example #15
Source File: user.ts    From monkeytype with GNU General Public License v3.0 6 votes vote down vote up
export async function removeTagPb(
  uid: string,
  _id: string
): Promise<UpdateResult> {
  const user = await getUser(uid, "remove tag pb");
  if (
    user.tags === undefined ||
    user.tags.filter((t) => t._id.toHexString() == _id).length === 0
  ) {
    throw new MonkeyError(404, "Tag not found");
  }
  return await getUsersCollection().updateOne(
    {
      uid: uid,
      "tags._id": new ObjectId(_id),
    },
    { $set: { "tags.$.personalBests": {} } }
  );
}
Example #16
Source File: collectStats.ts    From majsoul-api with MIT License 6 votes vote down vote up
export function collectStats(
	game: Store.GameResult<ObjectId>,
	version: StatsVersion,
	players?: Record<string, ObjectId | boolean>): (Stats & GamePlayerIds)[] {
	const baseStatsData = generateBaseStatsData(game);

	return selectPlayers(game, players).map(player => {
		const baseStats = collectBaseStats(game, player, baseStatsData);
		if (version === StatsVersion.None || version === StatsVersion.Undefined) {
			return {
				version: StatsVersion.None,
				...player,
				stats: baseStats,
			}
		}

		const firstStats = collectFirstStats(game, player, baseStats);
		if (version === StatsVersion.First) {
			return {
				version: StatsVersion.First,
				...player,
				stats: firstStats,
			}
		}

		const khanStats = collectKhanStats(game, player, firstStats);
		return {
			version: StatsVersion.Khan,
			...player,
			stats: khanStats,
		};
	});
}
Example #17
Source File: message-resolver.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
@Authorized()
  @Query(() => Messages)
  async getMessages(@Args() { after, before, limit, roomId }: getMessagesArgs) {
    const afterQuery = after && { $gt: new ObjectID(b64decode(after)) };
    const beforeQuery = before && { $lt: new ObjectID(b64decode(before)) };
    const criteria =
      afterQuery || beforeQuery
        ? {
            _id: { ...afterQuery, ...beforeQuery },
          }
        : {};

    let messages = await MessageModel.find({ roomId: roomId, ...criteria })
      .limit(limit + 1)
      .sort({ createdAt: afterQuery ? 0 : -1 })
      .populate("author")
      .lean();

    const hasNext = messages.length > limit - 1;
    if (hasNext) {
      messages = messages.slice(0, messages.length - 1);
    }
    const edges = messages.map(edge => ({
      cursor: b64encode(edge._id.toHexString()),
      node: edge,
    }));

    return {
      pageInfo: {
        hasNext: hasNext,
      },
      edges: edges.reverse(),
    };
  }
Example #18
Source File: ape-keys.ts    From monkeytype with GNU General Public License v3.0 6 votes vote down vote up
function getApeKeyFilter(
  uid: string,
  keyId: string
): Filter<MonkeyTypes.ApeKey> {
  return {
    _id: new ObjectId(keyId),
    uid,
  };
}
Example #19
Source File: message-resolver.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
@Authorized()
  @UseMiddleware(RateLimit({ limit: 1000 }))
  @Mutation(() => Message)
  async deleteMessage(
    @Arg("messageId") messageId: ObjectID,
    @Ctx() context: Context,
    @PubSub() pubsub: PubSubEngine
  ) {
    try {
      const message = await MessageModel.findOneAndDelete({
        _id: messageId,
        author: context.currentUser.id,
      });

      if (!message) throw new ApolloError("Cannot find message with ID");

      await message.populate("author").execPopulate();
      pubsub.publish(CONSTANTS.DELETE_MESSAGE, message.toObject());

      return message;
    } catch (err) {
      throw new ApolloError(err);
    }
  }
Example #20
Source File: update-secret.ts    From metroline with GNU General Public License v3.0 6 votes vote down vote up
export async function updateSecret(req: Request, res: Response): Promise<void> {
  const { secretId } = req.params;
  const secretObjectId = ObjectId.createFromHexString(secretId);
  await Secrets()
    .updateOne({ _id: secretObjectId }, {
      $set: {
        name: req.body.name,
        value: req.body.value,
        protectedBranchesOnly: req.body.protectedBranchesOnly,
        branches: req.body.branches,
      },
    });
  const secret = await Secrets().findOne({ _id: secretObjectId });
  res.json(serializeSecret(secret));
}
Example #21
Source File: message-subscriptions.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
@Subscription(returns => Message, {
    topics: CONSTANTS.DELETE_MESSAGE,
    filter: filterRoom,
  })
  onDeleteMessage(
    @Root() message: Message,
    @Arg("roomId") roomId: ObjectID
  ): Message {
    return message;
  }
Example #22
Source File: can-get-pipeline-guard.ts    From metroline with GNU General Public License v3.0 6 votes vote down vote up
canGetPipelineGuard = authorizationGuard(req => {
  const { pipelineId } = req.params;
  const user = getUser(req);
  return Pipelines()
    .findOne({ _id: ObjectId.createFromHexString(pipelineId) })
    .then(pipeline => (
      canPullRepo(pipeline.repoId, user)
    ));
})
Example #23
Source File: notification.test.ts    From convoychat with GNU General Public License v3.0 6 votes vote down vote up
initialize = async () => {
  const result = await gCall({
    source: `
      mutation createRoom($name: String!) {
        createRoom(name: $name) {
          name
          id
        }
      }
    `,
    variableValues: { name: ROOM_NAME },
  });
  ROOM_ID = result.data.createRoom.id;

  const context = createFakeContext();
  sender = await UserModel.findOne({ username: fakeUser2.username });
  await sendNotification({
    context: context as any,
    sender: new ObjectID(sender.id),
    receiver: new ObjectID(fakeUser.id),
    type: NOTIFICATION_TYPE.MENTION,
    payload: {
      roomName: result.data.createRoom?.name,
      message: "Hello world",
      messageId: "12345",
      roomId: result.data.createRoom?.id,
    },
  });
}
Example #24
Source File: seed-data.ts    From master-frontend-lemoncode with MIT License 6 votes vote down vote up
devMemberList: Member[] = [
  {
    _id: new ObjectId().toHexString(),
    login: 'brauliodiez',
    avatarUrl: 'https://avatars1.githubusercontent.com/u/1457912?v=4',
    organization: 'lemoncode',
  },
  {
    _id: new ObjectId().toHexString(),
    login: 'jaimesalas',
    avatarUrl: 'https://avatars.githubusercontent.com/u/7754966?v=4',
    organization: 'lemoncode',
  },
  {
    _id: new ObjectId().toHexString(),
    login: 'nasdan',
    avatarUrl: 'https://avatars2.githubusercontent.com/u/4374977?v=4',
    organization: 'lemoncode',
  },
]
Example #25
Source File: collectStats.ts    From majsoul-api with MIT License 6 votes vote down vote up
function collectKhanStats(
	game: Store.GameResult<ObjectId>,
	player: PlayerData,
	firstStats: FirstStats['stats'],
): KhanStats['stats'] {
	const khanStats = firstStats as KhanStats['stats'];
	khanStats.calls.kans = {
		ankan: 0,
		daiminkan: 0,
		rinshan: 0,
		shouminkan: 0,
		shouminkanRobbed: 0,
	};

	for (const round of game.rounds) {
		khanStats.calls.kans.ankan += round.playerStats[player.seat].calls.kans.ankan;
		khanStats.calls.kans.daiminkan += round.playerStats[player.seat].calls.kans.daiminkan;
		khanStats.calls.kans.rinshan += round.playerStats[player.seat].calls.kans.rinshan;
		khanStats.calls.kans.shouminkan += round.playerStats[player.seat].calls.kans.shouminkan;
		khanStats.calls.kans.shouminkanRobbed += round.playerStats[player.seat].calls.kans.shouminkanRobbed;
	}

	return khanStats;
}
Example #26
Source File: disable-repo.ts    From metroline with GNU General Public License v3.0 6 votes vote down vote up
export async function disableRepo(req: Request, res: Response): Promise<void> {
  const _id = ObjectId.createFromHexString(req.params.repoId);
  const apiToken = getApiToken(req);

  const { setup, repoId } = await Repos().findOne({ _id });

  if (!setup) {
    throw new BadRequestError('Repo is not setup');
  }

  const git = getGitServer(apiToken);
  await Promise.all([
    git
      .removeDeployKey(setup.deployKey, repoId)
      .catch(err => logger.error('Could not remove deploy key, you will have to do it manually', err)),
    git
      .removeWebhook(setup.webhook, repoId)
      .catch(err => logger.error('Could not remove webhook, you will have to do it manually', err)),
  ]);

  await Repos()
    .updateOne({ repoId }, { $unset: { setup: 1 } });

  res
    .status(204)
    .send();
}
Example #27
Source File: minimumVersion.ts    From majsoul-api with MIT License 6 votes vote down vote up
export function minimumVersion(game: Store.GameResult<ObjectId>): StatsVersion {
	if (game.version == null) {
		return StatsVersion.None;
	}

	switch (game.version) {
		case GameResultVersion.None:
			return StatsVersion.None;
		case GameResultVersion.First:
		case GameResultVersion.Second:
			return StatsVersion.First;
		case GameResultVersion.Third:
		case GameResultVersion.Fourth:
			return StatsVersion.Khan;
		default:
			return StatsVersion.None;
	}
}
Example #28
Source File: seed-data.ts    From master-frontend-lemoncode with MIT License 6 votes vote down vote up
prodMemberList: Member[] = [
  {
    _id: new ObjectId().toHexString(),
    login: 'gaearon',
    avatarUrl: 'https://avatars2.githubusercontent.com/u/810438?v=4',
    organization: 'facebook',
  },
  {
    _id: new ObjectId().toHexString(),
    login: 'acdlite',
    avatarUrl: 'https://avatars0.githubusercontent.com/u/3624098?v=4',
    organization: 'facebook',
  },
]
Example #29
Source File: RestApi.ts    From majsoul-api with MIT License 6 votes vote down vote up
private async getPhases(contestId: string): Promise<PhaseInfo> {
		const contest = await this.findContest(contestId, {
			projection: {
				_id: true,
				type: true,
				tourneyType: true,
				startTime: true,
				'teams._id': true,
				'teams.players._id': true,
				transitions: true,
				initialPhaseName: true,
				maxGames: true,
				subtype: true,
			}
		});

		if (contest == null) {
			return null;
		}

		const transitions = [
			{
				name: contest?.initialPhaseName ?? "予選",
				startTime: 0,
			} as ContestPhaseTransition<ObjectID>,
			...(contest.transitions ?? [])
		].sort((a, b) => a.startTime - b.startTime);

		return {
			contest,
			transitions,
			phases: transitions.map(({ startTime, name }, index) => ({
				index,
				name,
				startTime
			}))
		};
	}