NodeJs,Socket.IO,Typescript-在服务中访问套接字并发出消息

时间:2019-05-09 16:52:34

标签: node.js typescript express websocket socket.io

我是NodeJ的初学者。我正在尝试通过socket.io从OpenWeather API发布一些实时数据。我的代码如下:

App.ts

todo1.delete()

其中一个套接字控制器:

import {createSocketServer} from "socket-controllers";
import {SWeatherController} from "./modules/Weather/controller/SWeatherController";
import {config, ISchedule} from './config/schedules.config';
import {Container} from "typedi";
import {createConnection, getCustomRepository} from "typeorm";
import {WeatherRepository} from "./modules/Weather/repository/WeatherRepository";
const scheduler = require('node-schedule');


class App {
    private constructor() {
        createConnection().then(async () => {
            const repo = getCustomRepository(WeatherRepository);
            const socket = createSocketServer(3000, {
                controllers: [
                    SWeatherController
                ],
            });
            this.initSchedule();
        }) .catch(error => {
            console.log(error);
        });
    }

    private initSchedule() {
        config.schedules.forEach((schedule: ISchedule) => {
            scheduler.scheduleJob(schedule.date, function(fireDate){
                const service = Container.get(schedule.class);
                service[schedule.function]();
            });
        });
    }

    public static init() {
        return new App();
    }
}

export default App;

这是从api检索数据的服务:

import {SocketController, OnConnect, OnMessage, ConnectedSocket, MessageBody} from 'socket-controllers';
import {Container, Inject, Service} from 'typedi';
import {WeatherService} from '../service/WeatherService';
import {SEventType} from "../type/SEventType";
import {WeatherScheduleType} from "../type/WeatherScheduleType";
import {Weather} from "../entity/Weather";
import {ILocalizationMethod} from "../message/ILocalizationMethod";
import {ILocation} from "../message/ILocation";
const schedule = require('node-schedule');

@Service()
@SocketController()
export class SWeatherController {

    currentWeather: Weather;
    weatherService: WeatherService;

    constructor(
        @ConnectedSocket() socket,
    ) {
        this.connectedSocket = socket;
        this.weatherService = Container.get(WeatherService);
    }

    @OnConnect()
    async connect(
        @ConnectedSocket() socket
    ) {
        this.weatherService.getLastWeather().then((weather) => {
            this.currentWeather = weather;
            socket.emit(SEventType.SEND_WEATHER_DATA, this.currentWeather);
        });

        schedule.scheduleJob(WeatherScheduleType.CHECK_WEATHER_CHANGES, async () => {
            const lastWeather = await this.weatherService.getLastWeather();
            if (lastWeather.temp !== this.currentWeather.temp) {
                socket.emit(SEventType.SEND_WEATHER_DATA, lastWeather)
                console.log('old: ' + this.currentWeather);
                this.currentWeather = lastWeather;
                console.log('emitted: ' + this.currentWeather);
            }
        });
    }

    @OnMessage(SEventType.TOGGLE_LOCALIZATION_METHOD)
    toggleLocalizationMethod(
        @ConnectedSocket() socket: any,
        @MessageBody() message: ILocalizationMethod
    ) {
        console.log(message);
        try {
            this.weatherService.toggleLocalizationMethod(message).then(() => {
                this.weatherService.getLastWeather().then((weather) => {
                    this.currentWeather = weather;
                    socket.emit(SEventType.SEND_WEATHER_DATA, this.currentWeather);
                });

            });
        } catch (e) {
            console.log(e);
        } finally {

        }

    }
    @OnMessage(SEventType.UPDATE_LOCATION)
    changeLocation(
        @ConnectedSocket() socket: any,
        @MessageBody() message: ILocation
    ) {
        this.weatherService.updateLocation(message);
    }
    test() {
    }
}

如您所见,我正在使用套接字控制器库。目前,我正在运行独立的进程,用于从api和其他(在控制器中)访问数据以检查更新和发出。是否可以访问服务中的已连接套接字并直接从中发出消息?

PS。我知道代码看起来不太好,但这是我的第一个更大的节点应用程序,并且我不知道js开发约定和解决方案,我通常是PHP开发人员,并且我可能会从中习得一些习惯,因此我会提出任何批评。

0 个答案:

没有答案