npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nest-sockedis

v1.2.0

Published

NestJS Websocket Redis JWT

Downloads

6

Readme

Nest Sockedis

Nestjs, SocketIO, Redis, JWT

A library for much easier implementation of socketIO in the NestJs framework with user authentication using the jwt method Also implement operations with redis >

Installation

# npm
$ npm install --save nest-sockedis

# yarn
$ yarn add nest-sockedis

Environment config

Configures required to start inside the .env file

  • REDIS_HOST=127.0.0.1
  • REDIS_PORT=6379
  • REDIS_USERNAME=username
  • REDIS_PASSWORD=password
  • REDIS_DATABASE=0
  • JWT_TOKEN=strong_hash_string
  • JWT_ACCESS_TOKEN_TTL=13600 // 3600 second
  • JWT_REFRESH_TOKEN_TTL=15 // 15 days

Getting Started

Init the Adapter in main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { InitAdapters } from 'nest-sockedis';
// import { YourJwtService } from './jwt/jwt.service'; import your jwt service

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // InitAdapters(app, new YourJwtService()); inject your jwt service
  // or
  InitAdapters(app);
}

bootstrap();

Import WebsocketModule in the root module of the application. app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { WebsocketModule } from 'nest-sockedis';

@Module({
  imports: [WebsocketModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Your JwtService

import { Injectable, Logger } from '@nestjs/common';
import { BaseJwtService } from 'nest-sockedis';

@Injectable()
export class JwtService extends BaseJwtService {
  async findUserById(id: any) {
    // operation code here
  }
}

Methods available for this JwtService :

/**
 * create AccessToken and Refresh Token
 *
 * @param userId
 * @param clientId [any unique value related to the user]
 *
 * @returns {accessToken: '', refreshToken: ''}
 */
service.createTokens('userId', 'clientId');

Your ChatsGateway

import {
  SubscribeMessage,
  WebSocketGateway,
  MessageBody,
  ConnectedSocket,
} from '@nestjs/websockets';
import { UseGuards } from '@nestjs/common';
import { BaseGateway, JwtWsGuard } from 'nest-sockedis';

@WebSocketGateway({ path: '/chats' })
export class ChatsGateway extends BaseGateway {
  @SubscribeMessage('chats')
  @UseGuards(JwtWsGuard) /* Required for authentication */
  async onChats(
    @ConnectedSocket() client: any,
    @MessageBody() data: any /* You can use the dto class as type */,
  ) {
    /* user info */
    let user = client.auth.user;
    /* emit to chats event */
    this.server.to(client.id).emit('chats', { message: `hello ${user.id}` });
  }
}

Your ChatsModule

import { Module } from '@nestjs/common';
import { ChatsGateway } from './chats.gateway';
import { JwtWsGuard } from 'nest-sockedis';
@Module({
  providers: [JwtWsGuard, ChatsGateway],
})
export class ChatsModule {}

Client handshake to connect to the gateway

handshake?: {
    query?: {
      token?: string;
    };
    headers?: {
      authorization?: string;
    };
};

Your RedisService

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { RedisModule } from 'nest-sockedis';

@Module({
  imports: [RedisModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

import { Injectable, Logger } from '@nestjs/common';
import { RedisService } from 'nest-sockedis';

@Injectable()
export class YourRedisService {
  constructor(private readonly redisService: RedisService) {}

  async get(key: string): Promise<any> {
    return await this.redisService.get(key);
  }

  async set(key: string, value: any): Promise<void> {
    await this.redisService.set(key, value);
  }

  async hashSet(key: string, value: any): Promise<any> {
    return await this.redisService.hashSet(key, value);
  }

  async hashGet(key: string) {
    return await this.redisService.hashGet(key);
  }
}

Change Log

See Changelog for more information.

Contributing

Contributions welcome! See Contributing.

Author

Mostafa Gholami mst-ghi