typeorm#Not TypeScript Examples

The following examples show how to use typeorm#Not. 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: UsersRepository.ts    From gobarber-api with MIT License 6 votes vote down vote up
public async findAllProviders({
    execept_user_id,
  }: IFindAllProvidersDTO): Promise<User[]> {
    let users: User[];

    if (execept_user_id) {
      users = await this.ormRepository.find({
        where: {
          id: Not(execept_user_id),
        },
      });
    } else {
      users = await this.ormRepository.find();
    }

    return users;
  }
Example #4
Source File: UsersRepository.ts    From hotseat-api with MIT License 6 votes vote down vote up
public async findProviders({
    exceptUserId,
  }: IFindProvidersDTO): Promise<User[]> {
    const users = await this.ormRepository.find({
      where: {
        id: Not(exceptUserId),
        is_provider: true,
      },
    });

    return users;
  }
Example #5
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 #6
Source File: JtiLog.ts    From ADR-Gateway with MIT License 6 votes vote down vote up
async IsJtiUnique(jti:string,iss:string,sub:string):Promise<boolean> {
        try {
            let resolvedConnection = (await this.connection);

            let j = new JtiLog();
            j.jti = jti
            j.iss = iss
            j.sub = sub
            
            let inserted = await resolvedConnection.manager.save(j);

            let duplicateEntries = await resolvedConnection.manager.find(JtiLog,{
                iss: inserted.iss,
                jti: inserted.jti,
                sub: inserted.sub,
                id: Not(inserted.id)
            });

            if (duplicateEntries.length > 0) {
                return false;
            } else {
                return true;
            }
        } catch (err) {
            throw(err);
        }
    }
Example #7
Source File: Consent.ts    From ADR-Gateway with MIT License 6 votes vote down vote up
getActiveConsentByAccessToken = async (token:string,thumbprint:string,subjectPpid:string|undefined): Promise<Consent> => {
        let resolvedConnection = (await this.connection);
        let findOptions:any = {
            accessToken: token,
            clientCertThumbprint: thumbprint,
            // subjectPpid: subjectPpid,
            tokenRevocationStatus: Not(TokenRevocationStatus.REVOKED),
            accessTokenExpires: MoreThanOrEqual(moment().utc().toDate())
        };
        if (subjectPpid) {findOptions.subjectPpid = subjectPpid}
        let matchingConsent = await resolvedConnection.manager.findOneOrFail(
            Consent,findOptions);
        return matchingConsent;
    }
Example #8
Source File: spotter-time-series.ts    From aqualink-app with MIT License 6 votes vote down vote up
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: cve.ts    From crossfeed with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
populateVulnerabilitiesFromKEV = async () => {
  const response: AxiosResponse<CISACatalogOfKnownExploitedVulnerabilities> = await axios.get(
    KEV_URL
  );
  const { vulnerabilities: kevVulns } = response.data;
  for (const kevVuln of kevVulns) {
    const { affected = 0 } = await Vulnerability.update(
      {
        isKev: Not(true),
        cve: kevVuln.cveID
      },
      {
        isKev: true,
        kevResults: kevVuln as any
      }
    );
    if (affected > 0) {
      console.log(`KEV ${kevVuln.cveID}: updated ${affected} vulns`);
    }
  }
}
Example #10
Source File: UsersRepository.ts    From gobarber-project with MIT License 6 votes vote down vote up
public async findAllProviders({
    expect_user_id,
  }: IFindAllProvidersDTO): Promise<User[]> {
    let users: User[];

    if (expect_user_id) {
      users = await this.ormRepository.find({
        where: {
          id: Not(expect_user_id),
        },
      });
    } else {
      users = await this.ormRepository.find();
    }

    return users;
  }
Example #11
Source File: UsersRepository.ts    From GoBarber with MIT License 6 votes vote down vote up
public async findAllProviders({
    except_user_id,
  }: IFindAllProvidersDTO): Promise<User[]> {
    let users: User[];

    if (except_user_id) {
      users = await this.ormRepository.find({
        where: { id: Not(except_user_id) },
      });
    } else {
      users = await this.ormRepository.find();
    }

    return users;
  }
Example #12
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 #13
Source File: sensors.service.ts    From aqualink-app with MIT License 5 votes vote down vote up
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 #14
Source File: NpsController.ts    From NextLevelWeek with MIT License 5 votes vote down vote up
/**
     * 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 #15
Source File: purge.ts    From fosscord-server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
TODO: apply the delete bit by bit to prevent client and database stress
**/
router.post("/", route({ /*body: "PurgeSchema",*/ }), async (req: Request, res: Response) => {
	const { channel_id } = req.params;
	const channel = await Channel.findOneOrFail({ id: channel_id });
	
	if (!channel.guild_id) throw new HTTPError("Can't purge dm channels", 400);
	isTextChannel(channel.type);

	const rights = await getRights(req.user_id);
	if (!rights.has("MANAGE_MESSAGES")) {
		const permissions = await getPermission(req.user_id, channel.guild_id, channel_id);
		permissions.hasThrow("MANAGE_MESSAGES");
		permissions.hasThrow("MANAGE_CHANNELS");
	}
	
	const { before, after } = req.body as PurgeSchema;

	// TODO: send the deletion event bite-by-bite to prevent client stress

	var query: FindManyOptions<Message> & { where: { id?: any; }; } = {
		order: { id: "ASC" },
		// take: limit,
		where: {
		 channel_id,
		 id: Between(after, before), // the right way around
		 author_id: rights.has("SELF_DELETE_MESSAGES") ? undefined : Not(req.user_id)
		 // if you lack the right of self-deletion, you can't delete your own messages, even in purges
		 },
		relations: ["author", "webhook", "application", "mentions", "mention_roles", "mention_channels", "sticker_items", "attachments"]
	};
	

	const messages = await Message.find(query);
	const endpoint = Config.get().cdn.endpointPublic;
			
	if (messages.length == 0) { 
		res.sendStatus(304);
		return;
	}

	await Message.delete(messages.map((x) => ({ id: x })));
	
	await emitEvent({
		event: "MESSAGE_DELETE_BULK",
		channel_id,
		data: { ids: messages.map(x => x.id), channel_id, guild_id: channel.guild_id }
	} as MessageDeleteBulkEvent);

	res.sendStatus(204);
});
Example #16
Source File: check-video-streams.ts    From aqualink-app with MIT License 4 votes vote down vote up
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);
}