typeorm#In TypeScript Examples
The following examples show how to use
typeorm#In.
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: organization.controller.ts From bulwark with MIT License | 6 votes |
getArchivedOrgs = async (req: UserRequest, res: Response) => {
const orgs = await getConnection()
.getRepository(Organization)
.find({
where: { status: status.archived, id: In(req.userOrgs) },
});
if (!orgs) {
return res.status(404).json('Organizations do not exist');
}
res.json(orgs);
}
Example #2
Source File: reactions.ts From fosscord-server with GNU Affero General Public License v3.0 | 6 votes |
router.get("/:emoji", route({ permission: "VIEW_CHANNEL" }), async (req: Request, res: Response) => {
const { message_id, channel_id } = req.params;
const emoji = getEmoji(req.params.emoji);
const message = await Message.findOneOrFail({ id: message_id, channel_id });
const reaction = message.reactions.find((x) => (x.emoji.id === emoji.id && emoji.id) || x.emoji.name === emoji.name);
if (!reaction) throw new HTTPError("Reaction not found", 404);
const users = await User.find({
where: {
id: In(reaction.user_ids)
},
select: PublicUserProjection
});
res.json(users);
});
Example #3
Source File: Team.ts From liferay-grow with MIT License | 6 votes |
@Field(() => UserPaginationObject, { nullable: true })
async members(
@Arg('data', { nullable: true }) data?: UserPaginationInput,
): Promise<UserPaginationObject | null> {
const userDetailsIds = await getUserDetailsIdsByTeam(this.id);
if (userDetailsIds === null) {
return null;
}
const growMap = await GrowMap.find({
relations: ['user'],
where: { userDetails: In(userDetailsIds) },
});
const { pagination, rows } = await getAllPagination(
User,
{
...data,
find: { id: In(growMap.map(({ user }) => user.id)) },
},
['profile', 'growMap', 'growMap.userDetails', 'growMap.userDetails.role'],
);
return {
pagination,
rows,
};
}
Example #4
Source File: cve.ts From crossfeed with Creative Commons Zero v1.0 Universal | 6 votes |
identifyUnexpectedWebpages = async (allDomains: Domain[]) => {
const vulnerabilities: Vulnerability[] = [];
const webpages = await Webpage.find({
where: {
domain: { id: In(allDomains.map((e) => e.id)) },
status: MoreThanOrEqual(500)
},
relations: ['domain']
});
for (const webpage of webpages) {
vulnerabilities.push(
plainToClass(Vulnerability, {
domain: webpage.domain,
lastSeen: new Date(Date.now()),
title: `Unexpected status code ${webpage.status} for ${webpage.url}`,
severity: 'Low',
state: 'open',
source: 'webpage_status_code',
description: `${webpage.status} is not a normal status code that comes from performing a GET request on ${webpage.url}. This may indicate a misconfiguration or a potential for a Denial of Service (DoS) attack.`
})
);
}
await saveVulnerabilitiesToDb(vulnerabilities, false);
}
Example #5
Source File: organizations.ts From crossfeed with Creative Commons Zero v1.0 Universal | 6 votes |
list = wrapHandler(async (event) => {
if (!isGlobalViewAdmin(event) && getOrgMemberships(event).length === 0) {
return {
statusCode: 200,
body: JSON.stringify([])
};
}
await connectToDatabase();
let where: any = { parent: null };
if (!isGlobalViewAdmin(event)) {
where = { id: In(getOrgMemberships(event)), parent: null };
}
const result = await Organization.find({
where,
relations: ['userRoles', 'tags']
});
return {
statusCode: 200,
body: JSON.stringify(result)
};
})
Example #6
Source File: domains.ts From crossfeed with Creative Commons Zero v1.0 Universal | 6 votes |
get = wrapHandler(async (event) => {
let where = {};
if (isGlobalViewAdmin(event)) {
where = {};
} else {
where = { organization: In(getOrgMemberships(event)) };
}
await connectToDatabase();
const id = event.pathParameters?.domainId;
if (!isUUID(id)) {
return NotFound;
}
const result = await Domain.findOne(
{ id, ...where },
{
relations: ['services', 'organization', 'vulnerabilities']
}
);
return {
statusCode: result ? 200 : 404,
body: result ? JSON.stringify(result) : ''
};
})
Example #7
Source File: paginate.ts From nestjs-paginate with MIT License | 6 votes |
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: spotter-time-series.ts From aqualink-app with MIT License | 6 votes |
getSites = (
siteIds: number[],
hasSensorOnly: boolean = false,
siteRepository: Repository<Site>,
) => {
return siteRepository.find({
where: {
...(siteIds.length > 0 ? { id: In(siteIds) } : {}),
...(hasSensorOnly ? { sensorId: Not(IsNull()) } : {}),
},
});
}
Example #9
Source File: collections.service.ts From aqualink-app with MIT License | 6 votes |
async getHeatStressTracker() {
const heatStressData = await this.latestDataRepository.find({
metric: Metric.DHW,
value: MoreThanOrEqual(1),
});
const heatStressSiteIds = heatStressData.map((data) => data.siteId);
const heatStressSites = await this.siteRepository.find({
where: { id: In(heatStressSiteIds), approved: true },
});
return this.processCollection(heatStressTracker, heatStressSites);
}
Example #10
Source File: CashRateService.ts From cashcash-desktop with MIT License | 6 votes |
async removeRate(currencyId1: number, currencyId2: number) {
const repository = getManager().getCustomRepository(CashRateRepository);
const currencyIdList = [currencyId1, currencyId2];
const rateList: CashRate[] = await repository.find({
select: ['id'],
where: {
fromCurrencyId: In(currencyIdList),
toCurrencyId: In(currencyIdList),
},
});
this.cache.clear();
await repository.remove(rateList);
}
Example #11
Source File: CompanyResolver.ts From type-graphql-dataloader with MIT License | 6 votes |
@FieldResolver()
@Loader<string, Chair[]>(async (ids) => {
const chairs = await getRepository(Chair).find({
where: { company: { id: In([...ids]) } },
});
const chairsById = groupBy(chairs, "companyId");
return ids.map((id) => chairsById[id] ?? []);
})
chairs(@Root() root: Company) {
return (dataloader: DataLoader<string, Chair[]>) =>
dataloader.load(root.id);
}
Example #12
Source File: organization.controller.ts From bulwark with MIT License | 6 votes |
getActiveOrgs = async (req: UserRequest, res: Response) => {
const orgs = await getConnection()
.getRepository(Organization)
.find({
where: { status: status.active, id: In(req.userOrgs) },
});
if (!orgs) {
return res.status(404).json('Organizations do not exist');
}
return res.status(200).json(orgs);
}
Example #13
Source File: question.controller.ts From office-hours with GNU General Public License v3.0 | 5 votes |
@Post()
@Roles(Role.STUDENT)
async createQuestion(
@Body() body: CreateQuestionParams,
@User() user: UserModel,
): Promise<CreateQuestionResponse> {
const { text, questionType, groupable, queueId, force } = body;
const queue = await QueueModel.findOne({
where: { id: queueId },
relations: ['staffList'],
});
if (!queue) {
throw new NotFoundException(
ERROR_MESSAGES.questionController.createQuestion.invalidQueue,
);
}
if (!queue.allowQuestions) {
throw new BadRequestException(
ERROR_MESSAGES.questionController.createQuestion.noNewQuestions,
);
}
if (!(await queue.checkIsOpen())) {
throw new BadRequestException(
ERROR_MESSAGES.questionController.createQuestion.closedQueue,
);
}
const previousUserQuestions = await QuestionModel.find({
relations: ['queue'],
where: {
creatorId: user.id,
status: In(Object.values(OpenQuestionStatus)),
},
});
const previousCourseQuestion = previousUserQuestions.find(
(question) => question.queue.courseId === queue.courseId,
);
if (!!previousCourseQuestion) {
if (force) {
previousCourseQuestion.status = ClosedQuestionStatus.ConfirmedDeleted;
await previousCourseQuestion.save();
} else {
throw new BadRequestException(
ERROR_MESSAGES.questionController.createQuestion.oneQuestionAtATime,
);
}
}
try {
const question = await QuestionModel.create({
queueId: queueId,
creator: user,
text,
questionType,
groupable,
status: QuestionStatusKeys.Drafting,
createdAt: new Date(),
}).save();
return question;
} catch (err) {
console.error(err);
throw new HttpException(
ERROR_MESSAGES.questionController.saveQError,
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
Example #14
Source File: course.service.ts From office-hours with GNU General Public License v3.0 | 5 votes |
async getTACheckInCheckOutTimes(
courseId: number,
startDate: string,
endDate: string,
): Promise<TACheckinTimesResponse> {
const startDateAsDate = new Date(startDate);
const endDateAsDate = new Date(endDate);
if (startDateAsDate.getUTCDate() === endDateAsDate.getUTCDate()) {
endDateAsDate.setUTCDate(endDateAsDate.getUTCDate() + 1);
}
const taEvents = await EventModel.find({
where: {
eventType: In([
EventType.TA_CHECKED_IN,
EventType.TA_CHECKED_OUT,
EventType.TA_CHECKED_OUT_FORCED,
]),
time: Between(startDateAsDate, endDateAsDate),
courseId,
},
relations: ['user'],
});
const [checkinEvents, otherEvents] = partition(
taEvents,
(e) => e.eventType === EventType.TA_CHECKED_IN,
);
const taCheckinTimes: TACheckinPair[] = [];
for (const checkinEvent of checkinEvents) {
let closestEvent: EventModel = null;
let mostRecentTime = new Date();
const originalDate = mostRecentTime;
for (const checkoutEvent of otherEvents) {
if (
checkoutEvent.userId === checkinEvent.userId &&
checkoutEvent.time > checkinEvent.time &&
checkoutEvent.time.getTime() - checkinEvent.time.getTime() <
mostRecentTime.getTime() - checkinEvent.time.getTime()
) {
closestEvent = checkoutEvent;
mostRecentTime = checkoutEvent.time;
}
}
const numHelped = await QuestionModel.count({
where: {
taHelpedId: checkinEvent.userId,
helpedAt: Between(
checkinEvent.time,
closestEvent?.time || new Date(),
),
},
});
taCheckinTimes.push({
name: checkinEvent.user.name,
checkinTime: checkinEvent.time,
checkoutTime: closestEvent?.time,
inProgress: mostRecentTime === originalDate,
forced: closestEvent?.eventType === EventType.TA_CHECKED_OUT_FORCED,
numHelped,
});
}
return { taCheckinTimes };
}
Example #15
Source File: question.controller.ts From office-hours with GNU General Public License v3.0 | 5 votes |
@Patch(':questionId')
@Roles(Role.STUDENT, Role.TA, Role.PROFESSOR)
// TODO: Use queueRole decorator, but we need to fix its performance first
async updateQuestion(
@Param('questionId') questionId: number,
@Body() body: UpdateQuestionParams,
@UserId() userId: number,
): Promise<UpdateQuestionResponse> {
let question = await QuestionModel.findOne({
where: { id: questionId },
relations: ['creator', 'queue', 'taHelped'],
});
if (question === undefined) {
throw new NotFoundException();
}
const isCreator = userId === question.creatorId;
if (isCreator) {
// Fail if student tries an invalid status change
if (body.status && !question.changeStatus(body.status, Role.STUDENT)) {
throw new UnauthorizedException(
ERROR_MESSAGES.questionController.updateQuestion.fsmViolation(
'Student',
question.status,
body.status,
),
);
}
question = Object.assign(question, body);
try {
await question.save();
} catch (err) {
console.error(err);
throw new HttpException(
ERROR_MESSAGES.questionController.saveQError,
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
return question;
}
// If not creator, check if user is TA/PROF of course of question
const isTaOrProf =
(await UserCourseModel.count({
where: {
userId,
courseId: question.queue.courseId,
role: In([Role.TA, Role.PROFESSOR]),
},
})) > 0;
if (isTaOrProf) {
if (Object.keys(body).length !== 1 || Object.keys(body)[0] !== 'status') {
throw new UnauthorizedException(
ERROR_MESSAGES.questionController.updateQuestion.taOnlyEditQuestionStatus,
);
}
await this.questionService.validateNotHelpingOther(body.status, userId);
return await this.questionService.changeStatus(
body.status,
question,
userId,
);
} else {
throw new UnauthorizedException(
ERROR_MESSAGES.questionController.updateQuestion.loginUserCantEdit,
);
}
}
Example #16
Source File: Team.ts From liferay-grow with MIT License | 5 votes |
@Field(() => [KnowledgeArea])
async knowledgeArea(): Promise<KnowledgeArea[]> {
const userDetailsIds = await getUserDetailsIdsByTeam(this.id);
if (userDetailsIds === null) {
return [];
}
const growMap = await GrowMap.find({
relations: [
'user',
'knowledgeSkillDetails',
'knowledgeSkillDetails.knowledgeSkill',
'knowledgeSkillDetails.knowledgeSkill.area',
],
where: { userDetails: In(userDetailsIds) },
});
const areas: any = {};
for (const grow of growMap) {
for (const skillDetails of grow.knowledgeSkillDetails) {
const { area, ...skill } = skillDetails.knowledgeSkill;
if (!areas[area.id]) {
areas[area.id] = area;
}
if (areas[area.id].skills) {
const skillSetted = areas[area.id].skills.find(
({ id }: any) => id === skill.id,
);
if (!skillSetted) {
areas[area.id].skills.push(skill);
}
} else {
areas[area.id].skills = [skill];
}
}
}
const knowledgeAreas = [];
for (const area in areas) {
knowledgeAreas.push(areas[area]);
}
return knowledgeAreas;
}
Example #17
Source File: question.controller.ts From office-hours with GNU General Public License v3.0 | 5 votes |
@Post('group')
@Roles(Role.TA, Role.PROFESSOR)
async groupQuestions(
@Body() body: GroupQuestionsParams,
@UserId() instructorId: number,
): Promise<void> {
const questions = await QuestionModel.find({
where: {
id: In(body.questionIds),
},
relations: ['taHelped', 'creator'],
});
if (!questions.every((q) => q.groupable)) {
throw new BadRequestException(
ERROR_MESSAGES.questionController.groupQuestions.notGroupable,
);
}
await this.questionService.validateNotHelpingOther(
QuestionStatusKeys.Helping,
instructorId,
);
for (const question of questions) {
await this.questionService.changeStatus(
QuestionStatusKeys.Helping,
question,
instructorId,
);
}
const queue = await QueueModel.findOne({
where: {
id: body.queueId,
},
});
const creatorUserCourse = await UserCourseModel.findOne({
where: {
courseId: queue.courseId,
userId: instructorId,
},
});
await QuestionGroupModel.create({
creatorId: creatorUserCourse.id, // this should be usercourse id
queueId: body.queueId,
questions: questions,
}).save();
return;
}
Example #18
Source File: queue.service.ts From office-hours with GNU General Public License v3.0 | 5 votes |
/** Hide sensitive data to other students */
async personalizeQuestions(
queueId: number,
questions: ListQuestionsResponse,
userId: number,
role: Role,
): Promise<ListQuestionsResponse> {
if (role === Role.STUDENT) {
const newLQR = new ListQuestionsResponse();
Object.assign(newLQR, questions);
newLQR.queue = questions.queue.map((question) => {
const creator =
question.creator.id === userId
? question.creator
: pick(question.creator, ['id']);
// classToClass transformer will apply the @Excludes
return classToClass<Question>(
QuestionModel.create({ ...question, creator }),
);
});
newLQR.questionsGettingHelp = questions.questionsGettingHelp.map(
(question) => {
const creator =
question.creator.id === userId
? question.creator
: pick(question.creator, ['id']);
// classToClass transformer will apply the @Excludes
return classToClass<Question>(
QuestionModel.create({ ...question, creator }),
);
},
);
newLQR.yourQuestion = await QuestionModel.findOne({
relations: ['creator', 'taHelped'],
where: {
creatorId: userId,
queueId: queueId,
status: In(StatusSentToCreator),
},
});
newLQR.priorityQueue = [];
return newLQR;
}
return questions;
}
Example #19
Source File: scope_repository.ts From ts-oauth2-server with MIT License | 5 votes |
async getAllByIdentifiers(scopeNames: string[]): Promise<OAuthScope[]> {
return this.scopeRepo.find({ where: { name: In([...scopeNames]) } });
}
Example #20
Source File: scheduler.ts From crossfeed with Creative Commons Zero v1.0 Universal | 5 votes |
handler: Handler<Event> = async (event) => {
await connectToDatabase();
console.log('Running scheduler...');
const scanIds = event.scanIds || [];
if (event.scanId) {
scanIds.push(event.scanId);
}
const scanWhere = scanIds.length ? { id: In(scanIds) } : {};
const orgWhere = event.organizationIds?.length
? { id: In(event.organizationIds) }
: {};
const scans = await Scan.find({
where: scanWhere,
relations: ['organizations', 'tags', 'tags.organizations']
});
const organizations = await Organization.find({
where: orgWhere
});
const queuedScanTasks = await ScanTask.find({
where: {
scan: scanWhere,
status: 'queued'
},
order: {
queuedAt: 'ASC'
},
relations: ['scan']
});
const scheduler = new Scheduler();
await scheduler.initialize({
scans,
organizations,
queuedScanTasks,
orgsPerScanTask:
event.orgsPerScanTask ||
parseInt(process.env.SCHEDULER_ORGS_PER_SCANTASK || '') ||
1
});
await scheduler.runQueued();
await scheduler.run();
console.log('Finished running scheduler.');
}
Example #21
Source File: search-sync.ts From crossfeed with Creative Commons Zero v1.0 Universal | 5 votes |
handler = async (commandOptions: CommandOptions) => {
const { organizationId, domainId } = commandOptions;
console.log('Running searchSync');
await connectToDatabase();
const client = new ESClient();
const qs = Domain.createQueryBuilder('domain')
.leftJoinAndSelect('domain.organization', 'organization')
.leftJoinAndSelect('domain.vulnerabilities', 'vulnerabilities')
.leftJoinAndSelect('domain.services', 'services')
.having('domain.syncedAt is null')
.orHaving('domain.updatedAt > domain.syncedAt')
.orHaving('organization.updatedAt > domain.syncedAt')
.orHaving(
'COUNT(CASE WHEN vulnerabilities.updatedAt > domain.syncedAt THEN 1 END) >= 1'
)
.orHaving(
'COUNT(CASE WHEN services.updatedAt > domain.syncedAt THEN 1 END) >= 1'
)
.groupBy('domain.id, organization.id, vulnerabilities.id, services.id')
.select(['domain.id']);
if (organizationId) {
// This parameter is used for testing only
qs.where('organization.id=:org', { org: organizationId });
}
const domainIds = (await qs.getMany()).map((e) => e.id);
console.log(`Got ${domainIds.length} domains.`);
if (domainIds.length) {
const domainIdChunks = chunk(domainIds, DOMAIN_CHUNK_SIZE);
for (const domainIdChunk of domainIdChunks) {
const domains = await Domain.find({
where: { id: In(domainIdChunk) },
relations: ['services', 'organization', 'vulnerabilities']
});
console.log(`Syncing ${domains.length} domains...`);
await pRetry(() => client.updateDomains(domains), {
retries: 3,
randomize: true
});
await Domain.createQueryBuilder('domain')
.update(Domain)
.set({ syncedAt: new Date(Date.now()) })
.where({ id: In(domains.map((e) => e.id)) })
.execute();
}
console.log('Domain sync complete.');
} else {
console.log('Not syncing any domains.');
}
}
Example #22
Source File: BaseSqlRepository.ts From node-experience with MIT License | 5 votes |
async getInBy(condition: Record<string, string[]>): Promise<T[]>
{
const [key] = Object.keys(condition);
return await this.getBy({ [key]: In(condition[key]) });
}
Example #23
Source File: sst-time-series.ts From aqualink-app with MIT License | 5 votes |
getSites = (siteIds: number[], siteRepository: Repository<Site>) => {
return siteRepository.find({
where: siteIds.length > 0 ? { id: In(siteIds) } : {},
relations: ['historicalMonthlyMean'],
});
}
Example #24
Source File: data-uploads.service.ts From aqualink-app with MIT License | 5 votes |
async deleteDataUploads({ ids }: DataUploadsDeleteDto) {
await this.dataUploadsRepository.delete({ id: In(ids) });
}
Example #25
Source File: CashSplitRepository.ts From cashcash-desktop with MIT License | 5 votes |
async findByAccountId(accountIdList: number[]): Promise<CashSplit[]> {
return await this.find({
select: ['accountId', 'currencyId', 'amount', 'transactionDate'],
where: {
accountId: In(accountIdList),
},
});
}
Example #26
Source File: CashSplitRepository.ts From cashcash-desktop with MIT License | 5 votes |
async findByTransactionId(transactionIdList: number[]): Promise<CashSplit[]> {
return await this.find({
select: ['accountId', 'currencyId', 'amount'],
where: {
transactionId: In(transactionIdList),
},
});
}
Example #27
Source File: CashBudgetSplitRepository.ts From cashcash-desktop with MIT License | 5 votes |
async findByAccountId(accountIdList: number[]): Promise<CashBudgetSplit[]> {
return await this.find({
select: ['accountId', 'currencyId', 'amount', 'transactionDate'],
where: {
accountId: In(accountIdList),
},
});
}
Example #28
Source File: CashBudgetSplitRepository.ts From cashcash-desktop with MIT License | 5 votes |
async findByTransactionId(transactionIdList: number[]): Promise<CashBudgetSplit[]> {
return await this.find({
select: ['accountId', 'currencyId', 'amount'],
where: {
transactionId: In(transactionIdList),
},
});
}
Example #29
Source File: ItemsRepository.ts From ecoleta with MIT License | 5 votes |
public async findAllById(items: Array<string>): Promise<Item[]> {
const findAllItems = await this.ormRepository.find({
id: In(items),
});
return findAllItems;
}