typeorm#MoreThan TypeScript Examples

The following examples show how to use typeorm#MoreThan. 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: votes.ts    From Corsace with MIT License 6 votes vote down vote up
staffVotesRouter.delete("/:id/:user", async (ctx) => {
    const vote = await Vote.findOneOrFail({
        where: {
            ID: ctx.params.id,
            voter: ctx.params.user,
        },
        relations: [
            "category",
        ],
    });

    const otherUserVotes = await Vote.find({
        where: {
            ID: Not(ctx.params.id),
            voter: ctx.params.user,
            category: vote.category,
            choice: MoreThan(vote.choice),
        },
    });

    await vote.remove();
    await Promise.all([
        otherUserVotes.map(v => {
            v.choice--;
            return v.save();
        }),
    ]);

    ctx.body = {
        success: "removed",
    };
});
Example #2
Source File: voting.ts    From Corsace with MIT License 6 votes vote down vote up
votingRouter.delete("/:id", validatePhaseYear, isPhase("voting"), isEligible, async (ctx) => {
    const vote = await Vote.findOneOrFail({
        where: {
            ID: ctx.params.id,
            voter: ctx.state.user.ID,
        },
        relations: [
            "category",
        ],
    });

    const otherUserVotes = await Vote.find({
        where: {
            ID: Not(ctx.params.id),
            voter: ctx.state.user,
            category: vote.category,
            choice: MoreThan(vote.choice),
        },
    });

    await vote.remove();
    await Promise.all([
        otherUserVotes.map(v => {
            v.choice--;
            return v.save();
        }),
    ]);

    ctx.body = {
        success: "removed",
    };
});
Example #3
Source File: ConsentRequestLog.ts    From ADR-Gateway with MIT License 6 votes vote down vote up
NextRevocationToPropagate = async (cursor: ConsentRequestLog|undefined):Promise<ConsentRequestLog|undefined> => {
        let consent = await ((await this.connection)).manager.findOne(ConsentRequestLog,{
            revokedAt:"DataRecipient",
            revocationPropagationDate: IsNull(),
            revocationDate: MoreThan(moment().subtract(7,'days').toDate()),
            refreshToken: Not(IsNull()),
            id: MoreThan(cursor?.id || -1)
        })
        return consent;
    }
Example #4
Source File: db.ts    From avalanche-faucet-legacy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
// Returns how many nAVAX was sent in the past 24hours
async function getDailyUsage(key: ApiKey): Promise<BN>{
    if(!dbConnection) throw new Error("No database connection.")
    let now = Date.now()
    const HOUR_MS = 1000 * 60 * 60
    const DAY_MS = HOUR_MS * 24
    let yesterday = new Date(now - DAY_MS)

    let repo = await dbConnection.getRepository(Transaction)
    let res= await repo.find({
        where: {
            api_key: key,
            createdAt: MoreThan(yesterday)
        }
    })
    let sum = res.reduce((acc: BN, tx: Transaction) => {
        return acc.add(new BN(tx.amount))
    }, new BN(0))
    return sum
}
Example #5
Source File: cve.ts    From crossfeed with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
reopenClosedVulnerabilities = async () => {
  const oneWeekAgo = new Date(
    new Date(Date.now()).setDate(new Date(Date.now()).getDate() - 7)
  );
  const remediatedVulnerabilities = await Vulnerability.find({
    where: {
      state: 'closed',
      lastSeen: MoreThan(oneWeekAgo),
      substate: 'remediated'
    }
  });
  for (const vulnerability of remediatedVulnerabilities) {
    vulnerability.setState('unconfirmed', true, null);
    await vulnerability.save();
  }
}
Example #6
Source File: index.ts    From fosscord-server with GNU Affero General Public License v3.0 6 votes vote down vote up
// TODO: send over websocket
// TODO: check for GUILD_MEMBERS intent

router.get("/", route({}), async (req: Request, res: Response) => {
	const { guild_id } = req.params;
	const limit = Number(req.query.limit) || 1;
	if (limit > 1000 || limit < 1) throw new HTTPError("Limit must be between 1 and 1000");
	const after = `${req.query.after}`;
	const query = after ? { id: MoreThan(after) } : {};

	await Member.IsInGuildOrFail(req.user_id, guild_id);

	const members = await Member.find({
		where: { guild_id, ...query },
		select: PublicMemberProjection,
		take: limit,
		order: { id: "ASC" }
	});

	return res.json(members);
});
Example #7
Source File: paginate.ts    From nestjs-paginate with MIT License 6 votes vote down vote up
OperatorSymbolToFunction = new Map<FilterOperator, (...args: any[]) => FindOperator<string>>([
    [FilterOperator.EQ, Equal],
    [FilterOperator.GT, MoreThan],
    [FilterOperator.GTE, MoreThanOrEqual],
    [FilterOperator.IN, In],
    [FilterOperator.NULL, IsNull],
    [FilterOperator.LT, LessThan],
    [FilterOperator.LTE, LessThanOrEqual],
    [FilterOperator.BTW, Between],
    [FilterOperator.NOT, Not],
])
Example #8
Source File: request.controller.ts    From radiopanel with GNU General Public License v3.0 6 votes vote down vote up
@Post()
	@Permissions('requests/create')
	public async create(
		@Headers('authorization') authorization: string,
		@Body() request: RequestEntity,
		@Req() req: Request
	): Promise<any> {
		const remoteAddress = req.headers['x-real-ip'] as string || "internal";

		// first of all check for ban
		if (await this.banService.findOne({
			where: [
				{ identifier: remoteAddress, expiresAt: MoreThan(new Date()) },
				{ identifier: remoteAddress, expiresAt: IsNull()  }
			]
		})) {
			throw new NotAcceptableException('You have been banned from this radio');
		}

		if (await this.permissionService.hasPermission((req.user as any)?.uuid || req.headers.authorization, ['requests/ignore-timeout'])) {
			return this.requestService.create({
				requestOrigin: 'website',
				...request,
				requestContext: remoteAddress
			});
		}

		if (await this.requestService.findRecent(remoteAddress)) {
			throw new NotAcceptableException('Please wait before making another request');
		}

		return this.requestService.create({
			requestOrigin: 'website',
			...request,
			requestContext: remoteAddress
		});
	}
Example #9
Source File: influences.ts    From Corsace with MIT License 5 votes vote down vote up
influencesRouter.delete("/:id", isLoggedIn, currentMCA, async (ctx) => {
    const id = ctx.params.id;
    if (!/^\d+$/.test(id)) {
        ctx.body = { 
            error: "An influence ID is not provided!",
        };
        return;
    }

    const influence = await Influence.createQueryBuilder("influence")
        .leftJoinAndSelect("influence.user", "user", "influence.userID = user.ID")
        .leftJoinAndSelect("influence.influence", "influenceUser")
        .where("influence.ID = :id", { id })
        .andWhere("user.ID = :userID", { userID: ctx.state.user.ID })
        .getOne();
    if (!influence) {
        ctx.body = { 
            error: "Invalid influence ID!",
        };
        return;
    }
    const mca: MCA = ctx.state.mca;
    if (influence.year < mca.year) {
        ctx.body = {
            error: "You cannot remove influences for previous years!",
        };
        return;
    }

    await influence.remove();

    const influences = await Influence.find({
        user: ctx.state.user,
        year: mca.year,
        rank: MoreThan(influence.rank),
        mode: influence.mode,
    });

    await Promise.all(
        influences.map(i => {
            i.rank--;
            return i.save();
        })
    );
    ctx.body = {
        success: "removed",
    };
    return;
});
Example #10
Source File: index.ts    From fosscord-server with GNU Affero General Public License v3.0 5 votes vote down vote up
// https://discord.com/developers/docs/resources/channel#create-message
// get messages
router.get("/", async (req: Request, res: Response) => {
	const channel_id = req.params.channel_id;
	const channel = await Channel.findOneOrFail({ id: channel_id });
	if (!channel) throw new HTTPError("Channel not found", 404);

	isTextChannel(channel.type);
	const around = req.query.around ? `${req.query.around}` : undefined;
	const before = req.query.before ? `${req.query.before}` : undefined;
	const after = req.query.after ? `${req.query.after}` : undefined;
	const limit = Number(req.query.limit) || 50;
	if (limit < 1 || limit > 100) throw new HTTPError("limit must be between 1 and 100", 422);

	var halfLimit = Math.floor(limit / 2);

	const permissions = await getPermission(req.user_id, channel.guild_id, channel_id);
	permissions.hasThrow("VIEW_CHANNEL");
	if (!permissions.has("READ_MESSAGE_HISTORY")) return res.json([]);

	var query: FindManyOptions<Message> & { where: { id?: any; }; } = {
		order: { id: "DESC" },
		take: limit,
		where: { channel_id },
		relations: ["author", "webhook", "application", "mentions", "mention_roles", "mention_channels", "sticker_items", "attachments"]
	};
	

	if (after) {
		if (after > new Snowflake()) return res.status(422);
		query.where.id = MoreThan(after);
	}
	else if (before) { 
		if (before < req.params.channel_id) return res.status(422);
		query.where.id = LessThan(before);
	}
	else if (around) {
		query.where.id = [
			MoreThan((BigInt(around) - BigInt(halfLimit)).toString()),
			LessThan((BigInt(around) + BigInt(halfLimit)).toString())
		];
	}

	const messages = await Message.find(query);
	const endpoint = Config.get().cdn.endpointPublic;

	return res.json(
		messages.map((x: any) => {
			(x.reactions || []).forEach((x: any) => {
				// @ts-ignore
				if ((x.user_ids || []).includes(req.user_id)) x.me = true;
				// @ts-ignore
				delete x.user_ids;
			});
			// @ts-ignore
			if (!x.author) x.author = { id: "4", discriminator: "0000", username: "Fosscord Ghost", public_flags: "0", avatar: null };
			x.attachments?.forEach((y: any) => {
				// dynamically set attachment proxy_url in case the endpoint changed
				const uri = y.proxy_url.startsWith("http") ? y.proxy_url : `https://example.org${y.proxy_url}`;
				y.proxy_url = `${endpoint == null ? "" : endpoint}${new URL(uri).pathname}`;
			});
			
			/**
			Some clients ( discord.js ) only check if a property exists within the response,
			which causes erorrs when, say, the `application` property is `null`.
			**/
			
			for (var curr in x) {
				if (x[curr] === null)
					delete x[curr];
			}

			return x;
		})
	);
});
Example #11
Source File: form-entry.service.ts    From radiopanel with GNU General Public License v3.0 5 votes vote down vote up
public findRecent(requestContext: string, minutes: number): Promise<FormEntry | undefined> {
		return this.formEntryRepository.findOne({
			requestContext,
			createdAt: MoreThan(moment().subtract(minutes, 'minutes').toDate())
		});
	}
Example #12
Source File: request.service.ts    From radiopanel with GNU General Public License v3.0 5 votes vote down vote up
public async findRecent(requestContext: string): Promise<Request | undefined> {
		const tenant = await this.tenantService.findOne();

		return this.requestRepository.findOne({
			requestContext,
			createdAt: MoreThan(moment().subtract(tenant?.settings?.requestTimeout || 15, 'minutes').toDate())
		});
	}
Example #13
Source File: DatabaseSessionStoreAdapter.ts    From ZenTS with MIT License 5 votes vote down vote up
protected async getRecord(sessionId: string): Promise<DatabaseSessionStoreAdapterEntity> {
    return await this.repository.findOne({
      id: sessionId,
      expired_at: MoreThan(new Date()),
    })
  }
Example #14
Source File: heatmap.service.ts    From office-hours with GNU General Public License v3.0 5 votes vote down vote up
// Do not use this externally plz
  async _getHeatmapFor(courseId: number): Promise<Heatmap | false> {
    // The number of minutes to average across
    const BUCKET_SIZE_IN_MINS = 15;
    // Number of samples to gather per bucket
    const SAMPLES_PER_BUCKET = 3;
    console.time('heatmap');
    const recent = moment().subtract(8, 'weeks').toISOString();
    const questions = await QuestionModel.createQueryBuilder('question')
      .leftJoinAndSelect('question.queue', 'queue')
      .where('queue.courseId = :courseId', { courseId })
      .andWhere('question.status = :status', {
        status: ClosedQuestionStatus.Resolved,
      })
      .andWhere('question.helpedAt IS NOT NULL')
      .andWhere('question.createdAt > :recent', { recent })
      .orderBy('question.createdAt', 'ASC')
      .getMany();
    if (questions.length === 0) {
      return false;
    }

    const taEvents = await EventModel.find({
      where: { time: MoreThan(recent), courseId },
    });

    if (taEvents.length === 0) {
      return false;
    }

    const tz = (await CourseModel.findOne({ id: courseId })).timezone;

    function extractTimestamps(taEvents: EventModel[]) {
      const hours = [];
      taEvents.sort((a, b) => {
        return a.time.getTime() - b.time.getTime();
      });

      let iday = taEvents[0].time.getDate();
      let itime = taEvents[0].time.getTime();
      let etime = taEvents[0].time.getTime();
      for (let i = 1; i < taEvents.length; i++) {
        if (taEvents[i].time.getDate() == iday) {
          etime = taEvents[i].time.getTime();
        } else {
          hours.push([itime, etime]);
          iday = taEvents[i].time.getDate();
          itime = taEvents[i].time.getTime();
          etime = taEvents[i].time.getTime(); // new day
        }
      }

      hours.push([itime, etime]); // push last day.

      return hours;
    }

    let heatmap = this._generateHeatMapWithReplay(
      // Ignore questions that cross midnight (usually a fluke)
      questions.filter((q) => q.helpedAt.getDate() === q.createdAt.getDate()),
      extractTimestamps(taEvents),
      tz,
      BUCKET_SIZE_IN_MINS,
      SAMPLES_PER_BUCKET,
    );
    heatmap = arrayRotate(
      heatmap,
      -moment.tz.zone(tz).utcOffset(Date.now()) / BUCKET_SIZE_IN_MINS,
    );
    console.timeEnd('heatmap');
    return heatmap;
  }