Ably JWTを使用したコードの例



Ably JWTAuthメソッド
サービス登録時にバックエンドABLY KEYでAblyを有効にします.ioに対してrequestTokenが行われます.(図中のステップ1、2に示すように)
返されたally tokenを{"x-ally-token":返されたallyトークン値}の形式でペイロードにロードし、JWTトークンを発行してユーザーに返します.ユーザは、返されたトークン値に基づいてallyプラットフォームと通信します.(上の図のように、手順3、4、5)
コードの例

バックエンド

  • auth.service.ts
  • import { ConflictException, Injectable } from '@nestjs/common';
    import { JwtService } from '@nestjs/jwt';
    import { hash } from 'bcryptjs';
    import { User } from 'src/users/user.entity';
    import { UsersService } from 'src/users/users.service';
    
    @Injectable()
    export class AuthService {
      constructor(
        private readonly usersService: UsersService,
        private readonly jwtService: JwtService,
      ) {}
    ...... 중략 ......
      async login(userId: number) {
        const user = await this.usersService.findById(userId);
        const Ably = require('ably');
        var ably = new Ably.Rest.Promise({ key: process.env.ABLY_SECRET_KEY });
        const token = await ably.auth.requestToken({
          clientId: user.email,
        });
        const payload = { sub: userId, 'x-ably-token': token.token };
        return { token: this.jwtService.sign(payload) };
      }
    
      async reAbly() {
        const Ably = require('ably');
        var ably = new Ably.Rest.Promise({ key: process.env.ABLY_SECRET_KEY });
        const token = await ably.auth.requestToken();
        return token;
      }
    }
  • auth.controller.ts
  • @Public()
    @Get('/re-create')
      async reCreate() {
        return this.service.reAbly();
      } /// 해당 코드를 Auth Controller안에 추가
  • messages.service.ts(この部分は前の文章と同じ)
  • import { Injectable } from '@nestjs/common';
    import { TypeOrmService } from '../common/typeorm.service';
    import { Message } from './message.entity';
    
    @Injectable()
    export class MessagesService extends TypeOrmService(Message) {
     ..... 중략 ......
      async createMessage(userId: number, roomId: string, message: string) {
        this.publishMessage(userId, roomId, message);
        return this.repository.save({ roomId, userId, message });
      }
    
      publishMessage(userId: number, roomId: string, chat: string) {
        const Ably = require('ably');
        const ably = new Ably.Rest(process.env.ABLY_SECRET_KEY);
        const channel = ably.channels.get(roomId);
        channel.publish(userId.toString(), chat);
      }
    }

    フロントエンド

  • ChatPage.tsxまたはチャットウィンドウコンポーネントまたはページ
  • import Ably from 'ably/promises';
    import { Types } from 'ably';
    
    export const ChatPage = () => {
      const { id } = useParams<{ id: string }>();
      const [client, setClient] = useState<Ably.Realtime>();
      const [channel, setChannel] = useState<Types.RealtimeChannelPromise>();
      const [chat, setChat] = useState('');
      ...... 중략 ......
      useEffect(() => {
        if (client) return;
        const _client = new Ably.Realtime({
          token: localStorage.getItem('token') ?? '',
          authUrl: `${process.env.REACT_APP_API_URL}auth/re-create`,
          transports: ['web_socket'],
        });
        setClient(_client);
      }, [client]);
    
      useEffect(() => {
        if (!client || channel || !room) return;
        const _channel = client.channels.get(room.id);
        _channel.subscribe(() => refetchMessage());
        setChannel(_channel);
        return () => _channel.unsubscribe();
      }, [client, channel, room]);
    
      const createMessage = async (message: string) => {
        return await api.post(`/rooms/${room?.id}/message`, { message });
      };
     ...... 중략 ...... 
     };
    Realtime()のオプションについて簡単に説明します.
    token:localStorage.getItem('token') ?? ' 'セクションでは、受信したトークンが受信されていない場合に「」として処理するためのオプションが提供されます.
    authUrl:${process.env.REACT_APP_API_URL}auth/re-create allyトークンの有効期限が切れた場合に更新オプションを取得します
    transports:['web_socket']はally-transport-phoferenceをweb socketに固定するオプションです.
    前述したように、コードを追加すると、Callyチャットサービスの動作をAbly tokenで確認することができます.

    終わりの時。


    Ably.今回PCUPサービスを創出した際、IOというリアルタイムサービスを初めて利用し、韓国語の技術ブログがなく、公式文書が省略されているところが多いですが、この新サービスを利用した経験も価値があります.今後,チャット以外のユビキタスネットワークやGPS,Live Updateなどを利用する機会があれば,本シリーズに追加する.