RxJs DDP client based on node-ddp-client in Typescript (no meteor required)
MIT License
This is a simple WebSocket library for real time app like Chats, Notification, etc based on DDP protocol powered by RXjs
This library works well together with:
npm install rxjs-ddp-client
or
yarn add rxjs-ddp-client
// example/MyDDPClient.ts
//...
// Define your collections names
export enum MY_DDP_COLLECTIONS {
USERS = 'users',
CHATS = 'chats',
}
// Class methods implementations
connect() {
const ddpServerUrl = 'ws://localhost:8080';
super.connect(ddpServerUrl);
}
login() {
return this.callWithPromise('login', {
username: 'xxx',
password: 'xxx',
});
}
// Events called by DDPClient
onConnected() {
// DDP connected, now we can login and subscribe to the publications on the server
this.ddpStatus.isConnected = true;
this.ddpStatus.isDisconnected = false;
// Example: Login automatically when WebSocket is connected
this.login().then(() => {
this.subscribePublications();
this.observeCollections();
});
}
onDisconnected() {
// DDP disconnected, notify user
this.ddpStatus.isConnected = true;
this.ddpStatus.isDisconnected = false;
}
onSocketError(error) {
// Custom code on Socket error
}
// ...
}
// example/MyDDPCacheEngine.ts
export class MyDDPCacheEngine implements DDPCacheEngine {
constructor() {}
getItem(keyName: string) {
return Observable.of(localStorage.getItem(keyName));
}
setItem(keyName: string, value: any) {
return Observable.of(localStorage.setItem(keyName, value));
}
removeItem(keyName: string) {
return Observable.of(localStorage.removeItem(keyName));
}
}
VanillaJS
// app.ts
import { DDPCacheEngine } from 'rxjs-ddp-client';
import { MyDDPClient, MyDDPCacheEngine } from './src/utils/ddp';
const myDDPClient = new MyDDPClient();
// OPTION 1: Wrapper of LocalForage or any storage using Observable (methods must match to DDPCacheEngine interface)
// const _storageService = new MyLocalForageWrapper();
// OPTION 2: if you use Angular 2 you could consider using the StorageService of ng2-platform ([see ng2-platform repo](https://github.com/thomasgazzoni/ng2-platform))
// const _storageService = this._storageService; // Need to declare StorageService in the constructor
// OPTION 3: use the browser localStorage (using the example file my-ddp-cache-engine.ts above)
const _storageService = MyDDPCacheEngine;
myDDPClient.setCacheEngine(_storageService);
myDDPClient.connect();
Angular 2+
// app.component.ts
import { Component } from '@angular/core';
import { MyDDPClient } from './my-ddp-client';
import { MyDDPCacheEngine } from './my-ddp-cache-engine';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title = 'app';
constructor() {
this.init();
}
init() {
const myDDPClient = new MyDDPClient();
const myDDPCacheEngine = new MyDDPCacheEngine();
myDDPClient.initCacheStorage(myDDPCacheEngine);
myDDPClient.connect();
}
}
MIT