typeorm#IsNull TypeScript Examples
The following examples show how to use
typeorm#IsNull.
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: time-series.utils.ts From aqualink-app with MIT License | 7 votes |
getNOAASource = async (
site: Site,
sourcesRepository: Repository<Sources>,
) => {
return sourcesRepository
.findOne({
where: {
site,
type: SourceType.NOAA,
surveyPoint: IsNull(),
},
relations: ['site', 'site.historicalMonthlyMean'],
})
.then((source) => {
// If source exists return it
if (source) {
return source;
}
// Else create it and return the created entity
return sourcesRepository.save({
site,
type: SourceType.NOAA,
});
});
}
Example #2
Source File: time-series.utils.ts From aqualink-app with MIT License | 7 votes |
getSources = (
sites: Site[],
type: SourceType,
sourceRepository: Repository<Sources>,
) => {
return sites.map((site) =>
sourceRepository
.findOne({
relations: ['site'],
where: {
site,
surveyPoint: IsNull(),
type,
sensorId: type === SourceType.SPOTTER ? site.sensorId : IsNull(),
},
})
.then((source) => {
// If the source exists return it
if (source) {
return source;
}
// Else create it and return the created entity
return sourceRepository.save({
site,
type,
sensorId: type === SourceType.SPOTTER ? site.sensorId : undefined,
});
}),
);
}
Example #3
Source File: StorageProvider.ts From context-mod with MIT License | 6 votes |
protected async getInvite(id: string): Promise<InviteData | undefined | null> {
const qb = this.inviteRepo.createQueryBuilder('invite');
return await qb
.andWhere({id})
.andWhere(new Brackets((qb) => {
qb.where({_expiresAt: LessThanOrEqual(DateUtils.mixedDateToDatetimeString(dayjs().toDate()))})
.orWhere({_expiresAt: IsNull()})
})
).getOne();
}
Example #4
Source File: ConsentRequestLog.ts From ADR-Gateway with MIT License | 6 votes |
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 #5
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 #6
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 #7
Source File: request.controller.ts From radiopanel with GNU General Public License v3.0 | 6 votes |
@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 #8
Source File: sensors.service.ts From aqualink-app with MIT License | 5 votes |
async findSensors(): Promise<
(Site & { sensorPosition: GeoJSON; sensorType: SensorType })[]
> {
const sites = await this.siteRepository.find({
where: { sensorId: Not(IsNull()) },
});
// Get spotter data and add site id to distinguish them
const spotterData = await Bluebird.map(
sites,
(site) => {
if (site.sensorId === null) {
console.warn(`Spotter for site ${site.id} appears null.`);
}
return getSpotterData(site.sensorId!).then((data) => {
return {
id: site.id,
...data,
};
});
},
{ concurrency: 10 },
);
// Group spotter data by site id for easier search
const siteIdToSpotterData: Record<number, SpotterData & { id: number }> =
keyBy(spotterData, (o) => o.id);
// Construct final response
return sites.map((site) => {
const data = siteIdToSpotterData[site.id];
const longitude = getLatestData(data.longitude)?.value;
const latitude = getLatestData(data.latitude)?.value;
const sitePosition = site.polygon as Point;
// If no longitude or latitude is provided by the spotter fallback to the site coordinates
return {
...site,
applied: site.applied,
sensorPosition: createPoint(
longitude || sitePosition.coordinates[0],
latitude || sitePosition.coordinates[1],
),
sensorType: SensorType.SofarSpotter,
};
});
}
Example #9
Source File: NpsController.ts From NextLevelWeek with MIT License | 5 votes |
/**
* 1 2 3 4 5 6 7 8 9 10
* Detratores => 0 - 6
* Passivos => 7 - 8
* Promotores => 9 - 10
* (Número de promotores — número de detratores) / (número de respondentes) x 100
*/
async execute(req: Request, res: Response) {
const { survey_id } = req.params;
const surveysUsersRepository = getCustomRepository(
SurveysUsersRepository
);
const surveysUsers = await surveysUsersRepository.find({
survey_id,
value: Not(IsNull()),
});
// Dentro dessa resposta vamos filtrar os que são detratores, passivos ou promotores;
const detractor = surveysUsers.filter(
(survey) => survey.value >= 0 && survey.value <= 6
).length;
const passive = surveysUsers.filter(
(survey) => survey.value >= 7 && survey.value <= 8
).length;
const promoters = surveysUsers.filter(
(survey) => survey.value >= 9 && survey.value <= 10
).length;
// Total de respostas.
const totalAnswers = surveysUsers.length;
const calculate = Number(
(((promoters - detractor) / totalAnswers) * 100).toFixed(2)
);
return res.json({
detractor,
passive,
promoters,
totalAnswers,
nps: calculate,
});
}
Example #10
Source File: prune.ts From fosscord-server with GNU Affero General Public License v3.0 | 5 votes |
inactiveMembers = async (guild_id: string, user_id: string, days: number, roles: string[] = []) => {
var date = new Date();
date.setDate(date.getDate() - days);
//Snowflake should have `generateFromTime` method? Or similar?
var minId = BigInt(date.valueOf() - Snowflake.EPOCH) << BigInt(22);
/**
idea: ability to customise the cutoff variable
possible candidates: public read receipt, last presence, last VC leave
**/
var members = await Member.find({
where: [
{
guild_id,
last_message_id: LessThan(minId.toString())
},
{
last_message_id: IsNull()
}
],
relations: ["roles"]
});
console.log(members);
if (!members.length) return [];
//I'm sure I can do this in the above db query ( and it would probably be better to do so ), but oh well.
if (roles.length && members.length) members = members.filter((user) => user.roles?.some((role) => roles.includes(role.id)));
const me = await Member.findOneOrFail({ id: user_id, guild_id }, { relations: ["roles"] });
const myHighestRole = Math.max(...(me.roles?.map((x) => x.position) || []));
const guild = await Guild.findOneOrFail({ where: { id: guild_id } });
members = members.filter(
(member) =>
member.id !== guild.owner_id && //can't kick owner
member.roles?.some(
(role) =>
role.position < myHighestRole || //roles higher than me can't be kicked
me.id === guild.owner_id //owner can kick anyone
)
);
return members;
}
Example #11
Source File: backfill-phone-notifs.command.ts From office-hours with GNU General Public License v3.0 | 5 votes |
@Command({
command: 'backfill:phone-notifs',
describe:
'delete phone notifs with no userids, delete duplicate phone notifs, and forcibly set verified on existing phonenotifs',
autoExit: true,
})
async fix(): Promise<void> {
// Delete those without userids associated
const noUser = await PhoneNotifModel.delete({ userId: IsNull() });
console.log(`deleted ${noUser.affected} desktopnotifmodels with no userid`);
// delete at once
const toDelete: PhoneNotifModel[] = [];
// Delete duplicates
const dups = await PhoneNotifModel.createQueryBuilder('pnotif')
.select([`"phoneNumber"`, 'COUNT(*)'])
.groupBy('pnotif.phoneNumber')
.having('COUNT(*) > 1')
.getRawMany();
console.log(`found ${dups.length} dups`);
toDelete.push(...dups);
const valid: PhoneNotifModel[] = [];
let changedNum = 0;
// change to real number
const all = await PhoneNotifModel.find({ relations: ['user'] });
for (const p of all) {
const number = await this.twilioService.getFullPhoneNumber(p.phoneNumber);
if (number) {
if (number !== p.phoneNumber) {
changedNum += 1;
}
p.phoneNumber = number;
p.verified = true;
valid.push(p);
} else {
toDelete.push(p);
}
}
console.log(`Twilio changed ${changedNum} phone numbers to full num`);
await PhoneNotifModel.save(valid);
// Delete and make sure to disable phonenotif for user
console.log(
'deleting phone notifs: ',
toDelete.map((d) => d.phoneNumber),
);
if (toDelete.length) {
await PhoneNotifModel.delete(toDelete.map((d) => d.id));
}
const usersToDisable = (
await UserModel.find({
where: { phoneNotifsEnabled: true },
relations: ['phoneNotif'],
})
).filter((u) => !u.phoneNotif);
usersToDisable.forEach((u) => (u.phoneNotifsEnabled = false));
await UserModel.save(usersToDisable);
console.log(`disabled phonenotifs for ${usersToDisable.length} users`);
}
Example #12
Source File: check-video-streams.ts From aqualink-app with MIT License | 4 votes |
checkVideoStreams = async (
connection: Connection,
projectId: string,
) => {
const apiKey = process.env.FIREBASE_API_KEY;
const slackToken = process.env.SLACK_BOT_TOKEN;
const slackChannel = process.env.SLACK_BOT_CHANNEL;
const frontUrl = process.env.FRONT_END_BASE_URL;
// Check that the all necessary environment variables are set
if (!apiKey) {
logger.error('No google api key was defined');
return;
}
if (!slackToken) {
logger.error('No slack bot token was defined');
return;
}
if (!slackChannel) {
logger.error('No slack target channel was defined');
return;
}
if (!frontUrl) {
logger.error('No front url was defined');
return;
}
// Fetch sites with streams
const sitesWithStream = await connection.getRepository(Site).find({
where: { videoStream: Not(IsNull()) },
});
// Extract the youTube id from the URLs
const siteIdToVideoStreamDetails =
sitesWithStream.reduce<siteIdToVideoStreamDetails>((mapping, site) => {
const id = getYouTubeVideoId(site.videoStream!);
return {
...mapping,
[site.id]: {
id,
name: site.name,
siteId: site.id,
url: site.videoStream!,
// If no id exists, then url is invalid
error: id ? '' : 'Video stream URL is invalid',
},
};
}, {});
const youTubeIds = Object.values(siteIdToVideoStreamDetails)
.map((videoStreamDetails) => videoStreamDetails.id)
.filter((id) => id) as string[];
// Fetch the youTube video information for each id
const axiosResponse = await fetchVideoDetails(youTubeIds, apiKey);
// Validate that the streams are valid
// For ids with no errors an empty string is returned
const youTubeIdToError = checkVideoOptions(axiosResponse.data.items);
const blocks = Object.values(siteIdToVideoStreamDetails).reduce<
Exclude<SlackMessage['blocks'], undefined>
>((msgs, { id, siteId, url, name, error }) => {
const reportedError =
error ||
(!(id! in youTubeIdToError) && 'Video does not exist') ||
youTubeIdToError[id!];
if (!reportedError) {
return msgs;
}
const template = {
type: 'section',
text: {
type: 'mrkdwn',
text:
`*Site*: ${name} - ${getSiteFrontEndURL(siteId, frontUrl)}\n` +
`*Video*: ${url}\n` +
`*Error*: ${reportedError}`,
},
};
return [...msgs, template];
}, []);
// No irregular video streams were found
// So skip sending an alert on slack
if (!blocks.length) {
return;
}
// Create a simple alert template for slack
const messageTemplate = {
// The channel id is fetched by requesting the list on GET https://slack.com/api/conversations.list
// (the auth token should be included in the auth headers)
channel: slackChannel,
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: `Scheduled check of video streams in *${projectId}* instance`,
},
},
{
type: 'divider',
},
...blocks,
],
} as SlackMessage;
// Log message in stdout
logger.log(messageTemplate);
// Send an alert containing all irregular video stream along with the reason
await sendSlackMessage(messageTemplate, slackToken);
}