redis#createClient TypeScript Examples

The following examples show how to use redis#createClient. 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: subscriber.ts    From crypto-crawlers with Apache License 2.0 6 votes vote down vote up
async run(): Promise<void> {
    const client = createClient({ url: this.redisUrl });

    client.on('subscribe', (channel: string, count: number) => {
      console.info(
        `Subscribed to ${channel} successfully! There are ${count} subscribers on this channel so far.`,
      );
    });

    client.on('message', (channel: string, message: string) => {
      assert.equal(channel, this.channel);
      const msg = JSON.parse(message) as T;
      this.consumeFunc(msg);
    });

    client.subscribe(this.channel);
  }
Example #2
Source File: redis-service.ts    From nodejs-health-checker with MIT License 6 votes vote down vote up
export async function checkRedisClient(config: IntegrationConfig): Promise<HTTPChecker> {
  return new Promise((resolve, _) => {
    const client = createClient({
      host: config.host,
      db: config.db || 0,
      password: config.auth?.password,
      connect_timeout: config.timeout || Defaults.RedisTimeout,
      port: config.port || 6379,
    });
    client.on("error", (error: any) => {
      client.end(true);
      resolve({
        status: false,
        error,
      });
    });
    client.ping((status) => {
      client.end(true);
      resolve({
        status: status === null,
        error: status !== null ? status : undefined,
      });
    });
  });
}
Example #3
Source File: index.tsx    From vignette-web with MIT License 6 votes vote down vote up
getStaticProps: GetStaticProps = async ({ locale }) => {
  const client = createClient({
    url: process.env.REDIS_URL,
    password: process.env.REDIS_PW,
  })

  await client.connect()
  const data = await client.get(`contribs`)

  const parsed: cache = JSON.parse(data as string)

  return {
    props: {
      contributors: parsed.contributors,
      ...(await serverSideTranslations(locale as string, [
        `home`,
        `nav`,
        `common`,
      ])),
    }, // will be passed to the page component as props
    revalidate: 10,
  }
}
Example #4
Source File: updateContributors.ts    From vignette-web with MIT License 6 votes vote down vote up
setData = async (
  client: ReturnType<typeof createClient>,
  data: {
    contributors: contributor[]
    commits: number
    pullRequests: number
    openIssues: number
    timestamp: number
  },
) => {
  client.set(`contribs`, JSON.stringify(data))
}
Example #5
Source File: updateContributors.ts    From vignette-web with MIT License 6 votes vote down vote up
asdf = async () => {
  const client = createClient({
    url: process.env.REDIS_URL,
    password: process.env.REDIS_PW,
  })

  await client.connect()
  const data = await client.get(`contribs`)

  if (data == null) {
    const newData = await fetchData()

    setData(client, newData)
  } else {
    const parsed: cache = JSON.parse(data)

    if (Date.now() - parsed.timestamp > 3600000) {
      const newData = await fetchData()
      setData(client, newData)
    }
  }
}
Example #6
Source File: database.ts    From Adachi-BOT with MIT License 5 votes vote down vote up
constructor( port: number, auth_pass, logger: Logger, file: FileManagement ) {
		const host: string = process.env.docker === "yes" ? "redis" : "localhost";
		
		this.client = createClient( port, host, { auth_pass } );
		this.client.on( "connect", async () => {
			logger.info( "Redis 数据库已连接" );
		} );
	}
Example #7
Source File: cache.service.ts    From runebot with MIT License 5 votes vote down vote up
constructor(protected readonly configService: AppConfigService) {
    this._cache = createClient({ url: this.configService.bot.redisUri });
    this._cache.on('error', err => console.log('Redis Client Error', err));
    this._cache.connect();
  }
Example #8
Source File: publisher.ts    From crypto-crawlers with Apache License 2.0 5 votes vote down vote up
constructor(redisUrl: string) {
    this.client = createClient({ url: redisUrl });
  }
Example #9
Source File: rateLimiter.ts    From GoBarber with MIT License 5 votes vote down vote up
redisClient = createClient({
  host: REDIS_HOST,
  port: Number(REDIS_PORT),
  password: REDIS_PASS || undefined,
})
Example #10
Source File: redis.ts    From eosio-contract-api with GNU Affero General Public License v3.0 5 votes vote down vote up
constructor(host: string, port: number) {
        this.ioRedis = new Redis({ host, port });
        this.ioRedisSub = new Redis({ host, port });

        this.nodeRedis = createClient({ url: `redis://${host}:${port}` });
        this.nodeRedisSub = createClient({ url: `redis://${host}:${port}` });
    }
Example #11
Source File: admin.module.ts    From office-hours with GNU General Public License v3.0 5 votes vote down vote up
redisClient = createClient()
Example #12
Source File: index.ts    From commonwealth with GNU General Public License v3.0 4 votes vote down vote up
export async function setupWebSocketServer(
  httpServer: http.Server,
  rollbar: Rollbar,
  models: DB
) {
  // since the websocket servers are not linked with the main Commonwealth server we do not send the socket.io client
  // library to the user since we already import it + disable http long-polling to avoid sticky session issues
  const io = new Server(httpServer, {
    transports: ['websocket'],
    cors: {
      origin,
      methods: ['GET', 'POST'],
    },
  });

  io.use(authenticate);

  io.on('connection', (socket) => {
    log.trace(`${socket.id} connected`);
    socket.on('disconnect', () => {
      log.trace(`${socket.id} disconnected`);
    });
  });

  io.engine.on('connection_error', (err) => {
    // log.error(err.req);      // the request object
    // console.log(err.code);     // the error code, for example 1
    // console.log(err.message);  // the error message, for example "Session ID unknown"
    // console.log(err.context);  // some additional error context
    log.error('A WebSocket connection error has occurred', err);
  });

  // enables the admin analytics dashboard (creates /admin namespace)
  instrument(io, {
    auth: origin.includes("localhost") ? false : {
      type: "basic",
      username: WEBSOCKET_ADMIN_USERNAME,
      password: bcrypt.hashSync(WEBSOCKET_ADMIN_PASSWORD, WEBSOCKET_ADMIN_PASSWORD.length)
    }
  });

  log.info(`Connecting to Redis at: ${REDIS_URL}`);
  const pubClient = createClient({ url: REDIS_URL, socket: { tls: true, rejectUnauthorized: false } });

  const subClient = pubClient.duplicate();

  try {
    await Promise.all([pubClient.connect(), subClient.connect()]);
    // provide the redis connection instances to the socket.io adapters
    await io.adapter(<any>createAdapter(pubClient, subClient));
  } catch (e) {
    // local env may not have redis so don't do anything if they don't
    if (!origin.includes('localhost')) {
      log.error('Failed to connect to Redis!', e);
      rollbar.critical(
        'Socket.io server failed to connect to Redis. Servers will NOT share socket messages' +
          'between rooms on different servers!',
        e
      );
    }
  }

  // create the chain-events namespace
  const ceNamespace = createCeNamespace(io);
  const chatNamespace = createChatNamespace(io, models);

  try {
    const rabbitController = new RabbitMQController(
      <BrokerConfig>RabbitMQConfig
    );

    await rabbitController.init();
    await rabbitController.startSubscription(
      publishToCERoom.bind(ceNamespace),
      'ChainEventsNotificationsSubscription'
    );
  } catch (e) {
    log.error(
      `Failure connecting to ${process.env.NODE_ENV || 'local'}` +
        'RabbitMQ server. Please fix the RabbitMQ server configuration',
      e
    );
    if (!origin.includes('localhost'))
      rollbar.critical(
        'Failed to connect to RabbitMQ so the chain-evens notification consumer is DISABLED.' +
          'Handle immediately to avoid notifications queue backlog.',
        e
      );
  }
}
Example #13
Source File: about.tsx    From vignette-web with MIT License 4 votes vote down vote up
getStaticProps: GetStaticProps = async ({ locale }) => {
  const client = createClient({
    url: process.env.REDIS_URL,
    password: process.env.REDIS_PW,
  })

  await client.connect()
  const data = await client.get(`contribs`)

  const parsed: cache = JSON.parse(data as string)

  const ocData = await fetch(`https://api.opencollective.com/graphql/v2`, {
    headers: {
      'content-type': `application/json`,
      'api-key': process.env.OC_KEY as string,
    },
    body: JSON.stringify({
      query: `query account($slug: String) {
        collective(slug: $slug) {
          transactions{
            nodes {
              description(dynamic: true, full:true)

              kind

              amount{
                value
              }
            }

          }
          stats {
            totalNetAmountReceived {
              value
            }



            balanceWithBlockedFunds {
              value
            }

          }
      }
    }`,
      variables: { slug: `vignette` },
    }),

    method: `POST`,
  }).then(async (res) => res.json())

  const transactions = ocData.data.collective.transactions.nodes.filter(
    (i: Record<string, string>) =>
      i.kind == `EXPENSE` && i.description.toLowerCase().includes(`developer`),
  )

  let totalPaid = 0

  transactions.forEach(
    (t: { kind: string; amount: { value: number } }) =>
      (totalPaid -= t.amount.value),
  )

  totalPaid = Math.round(totalPaid * 100) / 100

  const { totalNetAmountReceived, balanceWithBlockedFunds } =
    ocData.data.collective.stats

  return {
    props: {
      netReceived: totalNetAmountReceived.value,
      balance: balanceWithBlockedFunds.value,
      totalPaid,
      ...parsed,
      ...(await serverSideTranslations(locale as string, [
        `about`,
        `nav`,
        `common`,
      ])),
    }, // will be passed to the page component as props
    revalidate: 600,
  }
}