核心
核心包中包含设计在任何JavaScript运行时间工作的API.
npm add @daniel-nagy/transporter
运输机作为ES模块分发. 一般说来,模块囊括了一种类型和导出功能,这些功能要么是该类型上的构造者,要么是操作者。 该模块与所封装的类型相同. 您将经常看到此类型以别名再导出 t。这是在功能编程语言中常见的常规,它允许从模块中调出类型而不打出名字两次,这感觉很恶心。 这使得使用命名空间导入的 Transporter 模块变得比较好一些. 譬如说,
import * as Observable from "@daniel-nagy/transporter/Observable";
// To access the type you need to type Observable twice 🤮.
const observable: Observable.Observable = Observable.of(1, 2, 3);
// Equivalent to the above. Not perfect but better.
const observable: Observable.t = Observable.of(1, 2, 3);
运输商在内部大量使用命名空间进口. 如果这让你担心震树那就别担心了 Webpack, Rollup, and esbuild 所有处理命名空间的进口罚款。 当涉及摇树时,命名空间出口可能会出问题。 虽然网络包装和Rollup 似乎也处理这些, 使建立立面.
API 密码
运输机包含以下模块.
行为主体
模块
A 类 BehaviorSubject 是一个 Subject 重新显示订阅时的最新值.
类型
构造器
方法
行为主体
类型
class BehaviorSubject<T> extends Subject<T> {}
A 类 Subject 重放最后一个释放的值.
员额
构造器
function of<T>(value: T): BehaviorSubject<T>;
创建新 BehaviorSubject 类型初始值 T。 。 。 .
示例
import * as BehaviorSubject from "@daniel-nagy/transporter/BehaviorSubject";
BehaviorSubject.of("👍").subscribe(console.log);
获取值
方法
getValue(): T;
这个 getValue 方法可以用来同步取回该工具所持有的值 BehaviorSubject如果 BehaviorSubject 处于错误状态 getValue 将丢出错误.
示例
import * as BehaviorSubject from "@daniel-nagy/transporter/BehaviorSubject";
BehaviorSubject.of("👍").getValue();
缓存
模块
A 类 Cache 可用于记忆远程函数调用。 运输商保证代理人具有优惠稳定性,因此其他记忆性API也可能与运输商兼容.
为了纪念一个函数,它的论点必须是可序列的。 稳定算法用于序列化函数的参数并索引缓存. 缓存支持任何类型的参数 SuperJson。 。 。 .
类型
构造器
方法
缓存
类型
class Cache {}
A 类 Cache 用于记忆远程函数调用。 A 类 Cache 被函数及其参数所双键.
输入
构造器
function init(): Cache;
创建新 Cache。 。 。 .
示例
import * as Cache from "@daniel-nagy/transporter/Cache";
const cache = Cache.init();
添加
方法
add(func: JsFunction.t, args: SuperJson.t[], value: unknown): void;
为指定的函数和参数添加缓存值。 内部使用 memo 方法,这是为缓存添加一个值的首选方法.
示例
import * as Cache from "@daniel-nagy/transporter/Cache";
const identity = (value) => value;
Cache.init().add(identity, "🥸", "🥸");
获取
方法
get<Args extends SuperJson.t[], Return>(
func: (...args: Args) => Return,
args: Args
): Return | NotFound;
从缓存中获取一个值 。 回返 NotFound 如果该值不存在.
示例
import * as Cache from "@daniel-nagy/transporter/Cache";
const identity = (value) => value;
Cache.init().get(identity, "🥸"); // NotFound
有过
方法
has(func: JsFunction.t, args?: SuperJson.t[]): boolean
检查该值是否在缓存中 。 如果没有提供论据,它就会返回 true 如果函数有任何值被缓存.
示例
import * as Cache from "@daniel-nagy/transporter/Cache";
const identity = (value) => value;
Cache.init().has(identity, "🥸"); // false
备忘
方法
memo<Args extends SuperJson.t[], Return>(
func: (...args: Args) => Return
): (...args: Args) => Return
以一个函数作为输入并返回与输出相同的函数的记忆版本. 使用被纪念的函数是缓存中增加值的首选方式.
示例
import * as Cache from "@daniel-nagy/transporter/Cache";
const identity = (value) => value;
const cache = Cache.init();
const memo = Cache.memo(identity);
memo("🥸");
cache.has(identity, "🥸"); // true
删除
方法
remove(func: JsFunction.t, args?: SuperJson.t[]): boolean
删除缓存中的值。 回返 true 如果找到并删除了该值。 如果不提供参数,则该函数的所有值将被删除.
示例
import * as Cache from "@daniel-nagy/transporter/Cache";
const identity = (value) => value;
const cache = Cache.init();
const memo = Cache.memo(identity);
memo("🥸");
cache.remove(identity, "🥸"); // true
更新
方法
update<Args extends SuperJson.t[], Return>(
func: (...args: Args) => Return,
args: Args,
callback: (value: Return) => Return
): void
更新缓存中的值。 回调函数将接收缓存中的当前值. 如果值存在缓存误差, 则什么都不做 .
示例
import * as Cache from "@daniel-nagy/transporter/Cache";
const identity = (value) => value;
const cache = Cache.init();
const memo = Cache.memo(identity);
memo("🥸");
cache.update(identity, "🥸", () => "🤓");
喷出器
模块
一个 Injector 是 IoC 容器,可用于向 Transporter 引用的函数注入依赖性.
类型
构造器
方法
职能
喷出器
类型
class Injector {}
一个 Injector 是一个依赖容器。 可使用标记从容器中添加或读取数值.
标记
类型
type Tag<Value> {}
A 类 Tag 是一个与单一依赖类型相接并用来索引容器的值.
空
构造器
function empty(): Injector;
创建新空 Injector。 。 。 .
示例
import * as Injector from "@daniel-nagy/transporter/Injector";
const injector = Injector.empty();
标记
构造器
function Tag<T>(): Tag<T>;
创建新 Tag。 。 。 .
示例
import * as Injector from "@daniel-nagy/transporter/Injector";
type Session = {
userId?: string;
};
const SessionTag = Injector.Tag<Session>();
添加
方法
function add<Value>(tag: Tag<Value>, value: Value): Injector;
向容器中添加一个值.
示例
import * as Injector from "@daniel-nagy/transporter/Injector";
type Session = {
userId?: string;
};
const SessionTag = Injector.Tag<Session>();
const Session: Session = { userId: "User_123" };
Injector.empty().add(SessionTag, Session);
获取
方法
function get(tag: Tag<unknown>): unknown;
使用 Tag。 。 。 .
示例
import * as Injector from "@daniel-nagy/transporter/Injector";
const tag = Injector.Tag<string>();
Injector.empty().get(tag);
获取标签
函数
function getTags(func: JsFunction.t): : Tag<unknown>[];
从函数返回标签列表 provide。如果函数没有 DI 元数据,则返回空列表.
示例
import * as Injector from "@daniel-nagy/transporter/Injector";
const getUser = Injector.provide([Prisma, Session], (prisma, session) =>
prisma.user.findUnique({ where: { id: session.userId } })
);
Injector.getTags(getUser);
提供
函数
function provide<
const Tags extends readonly Tag<unknown>[],
const Args extends [...Values<Tags>, ...unknown[]],
const Return
>(
tags: Tags,
func: (...args: Args) => Return
): (...args: JsArray.DropFirst<Args, JsArray.Length<Tags>>) => Return;
返回一个新的函数,该函数包含一个存储为元数据的标签列表。 新函数的调用签名将忽略任何被注入的依赖性 。 通用函数的类型参数将推广到新函数.
示例
import * as Injector from "@daniel-nagy/transporter/Injector";
const getUser = Injector.provide(
[Prisma, Session],
<S extends Prisma.UserSelect>(prisma, session, select: S) =>
prisma.user.findUnique({ where: { id: session.userId }, select })
);
// $ExpectType
// const getUser = <S extends Prisma.UserSelect>(
// select: S
// ) => Prisma.Prisma__User<S> | null;
贾森
模块
A 类 Json 类型可作为子议定书的数据类型。 如果您的通信频道两端都是 JavaScript 运行时间, 您可以使用 超级杰森 模块代替更大的一组类型.
类型
职能
贾森
类型
export type Json =
| null
| number
| string
| boolean
| { [key: string]: Json }
| Json[];
系JSON值.
序列化
function serialize(value: Json): string;
以决定性的方式序列化一个 JSON 值,这样,如果两个字符串编码到相同的值,它们就是相等的.
示例
import * as Json from "@daniel-nagy/transporter/Json";
Json.serialize({ name: "Jane Doe" });
排序深处
function sortDeep(value: Json): Json;
递归排序对象的属性。 矩阵值保留其排序顺序 .
示例
import * as Json from "@daniel-nagy/transporter/Json";
Json.sortDeep({
c: "c",
b: [{ f: "f", e: "e" }, 12],
a: "a"
});
// $ExpectType
// {
// a: "a",
// b: [{ e: "e", f: "f" }, 12],
// c: "c"
// }
消息
模块
定义传送器信件协议。 电文的制作和解释应被视为内部的。 然而,可以截取信息并进行自己的逻辑或编码.
类型
常数
职能
调用功能
类型
type CallFunction<Args> = {
readonly address: string;
readonly args: Args;
readonly id: string;
readonly noReply: boolean;
readonly path: string[];
readonly protocol: "transporter";
readonly type: Type.Call;
readonly version: Version;
};
A 类 Call 消息发送到服务器以调用远程函数.
错误
类型
type Error<Error> = {
readonly address: string;
readonly error: Error;
readonly id: string;
readonly protocol: "transporter";
readonly type: Type.Error;
readonly version: Version;
};
一个 Error 消息在调用远程函数时发送给客户端.
垃圾组装
类型
type GarbageCollect = {
readonly address: string;
readonly id: string;
readonly protocol: "transporter";
readonly type: Type.GarbageCollect;
readonly version: Version;
};
A 类 GarbageCollect 当客户端上处理一个代理服务器时,信件会被发送到服务器.
消息
类型
type Message<Value> =
| CallFunction<Value[]>
| Error<Value>
| GarbageCollect
| SetValue<Value>;
不同信息类型的歧视结合.
设置值
类型
type SetValue<Value> = {
readonly address: string;
readonly id: string;
readonly protocol: "transporter";
readonly type: Type.Set;
readonly value: Value;
readonly version: Version;
};
A 类 Set 消息在调用远程函数后发送给客户端.
类型
类型
enum Type {
Call = "Call",
Error = "Error",
GarbageCollect = "GarbageCollect",
Set = "Set"
}
不同信息类型的可假设 .
版本
类型
type Version = `${number}.${number}.${number}`;
语义版字符串.
议定书
常数
const protocol = "transporter";
协议名称.
版本
常数
const version: Version;
协议的版本.
兼容
函数
function isCompatible(messageVersion: Version): boolean;
如果信件符合当前协议版本, 则返回真实值 。 A 类 如果信件的主要版本和次要版本相同,则视为兼容.
示例
import * as Message from "@daniel-nagy/transporter/Message";
Message.isCompatible(message);
图像
函数
function isMessage<T, Value>(
message: T | Message<Value>
): message is Message<Value>;
如果值是 Transporter 消息, 返回 True .
示例
import * as Message from "@daniel-nagy/transporter/Message";
Message.isMessage(value);
剖析度
函数
function parseVersion(
version: Version
): [major: string, minor: string, patch: string];
解析一个语义版本字符串并返回一个翻转的版本段.
示例
import * as Message from "@daniel-nagy/transporter/Message";
Message.parseVersion(message.version);
元数据
模块
元数据模块允许从代理中提取信息.
类型
职能
元数据
类型
type Metadata = {
/**
* The id of the client agent managing this proxy.
*/
clientAgentId: string;
/**
* The path to the value in the original object.
*/
objectPath: string[];
};
包含关于代理对象的信息.
获取
function get<Proxy extends object>(proxy: Proxy): Metadata | null;
返回关于代理的元数据 。 如果对象不是代理, 则返回 null。 。 。 .
示例
import * as Metadata from "@daniel-nagy/transporter/Metadata";
const metadata = Metadata.get(obj);
可观察
模块
可观察模块提供 反应X 类似 rxjs (韩语)。如果你大量使用可观察器,那么你可以决定使用rxjs.
运输器可观测物应与可观测rxj相通。 如果你遇到问题 转换成或从rxjs 观察, 那么你可以报告这些问题.
运输商的行为可能与同名的rxjs运营商不同.
类型
构造器
方法
职能
缓冲
类型
class BufferOverflowError extends Error {}
如果发生缓冲溢出而缓冲溢出策略是 Error。 。 。 .
流动战略
类型
enum BufferOverflowStrategy {
/**
* Discard new values as they arrive.
*/
DropLatest = "DropLatest",
/**
* Discard old values making room for new values.
*/
DropOldest = "DropOldest",
/**
* Error if adding a new value to the buffer will cause an overflow.
*/
Error = "Error"
}
指定发生缓冲溢出时要做什么.
缓冲选项
类型
type BufferOptions = {
/**
* The max capacity of the buffer. The default is `Infinity`.
*/
limit?: number;
/**
* How to handle a buffer overflow scenario. The default is `Error`.
*/
overflowStrategy?: BufferOverflowStrategy;
};
执行缓冲的运算符的选项 .
空错误
类型
class EmptyError extends Error {}
如果观测到的值在排放出单一值之前完成,则预期值会释放的运算符可能会抛出.
活动
类型
interface Event {
type: string;
}
代表 JavaScript 事件 。 由于 Transporter 不包括特定运行时间的类型,所以是必需的.
事件目标
类型
interface EventTarget {
addEventListener(type: string, callback: (event: Event) => void): void;
dispatchEvent(event: Event): boolean;
removeEventListener(type: string, callback: (event: Event) => void): void;
}
代表 JavaScript 事件目标 。 由于 Transporter 不包括特定运行时间的类型,所以是必需的.
可观察
类型
class Observable<T> implements ObservableLike<T> {}
可观测器是懒惰地推动数据结构,既能发出同步值又能同步值. 观察者是独有的,与承诺不同,他们可能永远不放出某种价值,或可能放出许多价值.
可观察的类似
类型
interface ObservableLike<T> {
subscribe(observerOrNext?: Observer<T> | ((value: T) => void)): Subscription;
}
一个值是 ObservableLike 如果它有一个 subscribe 使用一个函数或 Observer 作为输入和返回a Subscription。 。 。 .
观察员
类型
type Observer<T> = {
next?(value: T): void;
error?(error: unknown): void;
complete?(): void;
};
一个 Observer 订阅一个可观察的.
运算符
类型
type Operator<T, U> = (observable: ObservableLike<T>) => ObservableLike<U>;
一个 Operator 是一个以可观测为输入的函数,返回新的可观测为输出的函数.
订阅
类型
type Subscription = {
unsubscribe(): void;
};
A 类 Subscription 当观察者订阅一个可观察者时,将返回.
状态
类型
enum State {
Complete = "Complete",
Error = "Error",
NotComplete = "NotComplete",
Unsubscribed = "Unsubscribed"
}
对于不同可观测状态的歧视类型.
超时错误
类型
class TimeoutError extends Error {}
被丢弃 timeout 运算符,如果某一数值未在指定时间内出出.
克龙
构造器
function cron<T>(
interval: number,
callback: () => T | Promise<T>
): Observable<T>;
创建一个可观察到的函数,在正常间隔中调用函数,并释放该函数返回的值.
示例
import * as Observable from "@daniel-nagy/transporter/Observable";
Observable.cron(1000, () => Math.random()).subscribe(console.log);
失败
构造器
function fail<E>(errorOrCallback: E | (() => E)): Observable<never>;
创建一个可观察到的、会立即与提供的值出错的变量 。 如果值是一个函数,则该函数将被调用以获得值.
示例
import * as Observable from "@daniel-nagy/transporter/Observable";
Observable.fail("💩");
从
构造器
function from<T>(observable: ObservableLike<T> | PromiseLike<T>): Observable<T>;
创建新 Observable 从一个可观察的或可承诺的物体发出的.
示例
import * as Observable from "@daniel-nagy/transporter/Observable";
Observable.from(Promise.resolve("👍"));
从Event 开始
构造器
function function fromEvent<T extends Event>(target: EventTarget, type: string): Observable<T>;
从事件对象和事件类型创建热可观测值.
示例
import * as Observable from "@daniel-nagy/transporter/Observable";
Observable.fromEvent(button, "click");
员额
构造器
function of<T>(...values: [T, ...T[]]): Observable<T>;
创建新 Observable 使每个参数同步发出,然后完成.
示例
import * as Observable from "@daniel-nagy/transporter/Observable";
Observable.of(1, 2, 3).subscribe(console.log);
管道
方法
pipe<A, B, ..., M, N>(
...operations: [Operator<A, B>, ..., Operator<M, N>]
): Observable<N>
允许链路运算符执行流量控制.
示例
import * as Observable from "@daniel-nagy/transporter/Observable";
Observable.of(1, "2", 3, 4.5).pipe(
filter(Number.isInteger),
map((num) => num * 2)
);
订阅
方法
subscribe(observerOrNext?: Observer<T> | ((value: T) => void)): Subscription
原因 a/ Observer 开始从可观测值中接收这些值.
示例
import * as Observable from "@daniel-nagy/transporter/Observable";
Observable.of(1, 2, 3).subscribe(console.log);
缓冲
函数
function bufferUntil<T, S>(
signal: ObservableLike<S>,
options?: BufferOptions
): (observable: ObservableLike<T>) => Observable<T>;
缓冲释放值直到信号发出或完成 。 一旦信号发出或完成缓冲值会同步被放出.
示例
import * as Observable from "@daniel-nagy/transporter/Observable";
import * as Subject from "@daniel-nagy/transporter/Subject";
const signal = Subject.init();
Observable.of(1, 2, 3).pipe(bufferUntil(signal)).subscribe(console.log);
setTimeout(() => signal.next(), 2000);
抓取错误
函数
function catchError<T>(
callback: <E>(error: E) => ObservableLike<T>
): (observable: ObservableLike<T>) => Observable<T>;
捕捉到上游观测到的错误。 调用函数可以返回一个新的可观察到的以从错误中恢复. 新的观测器将完全取代旧的.
示例
import * as Observable from "@daniel-nagy/transporter/Observable";
Observable.of(1, 2, 3)
.pipe(
Observable.flatMap(() => Observable.fail("💩")),
Observable.catchError(() => Observable.of(4, 5, 6))
)
.subscribe(console.log);
过滤器
函数
function filter<T, S extends T>(
callback: ((value: T) => value is S) | ((value: T) => boolean)
): (observable: ObservableLike<T>) => Observable<S>;
选择保留回调返回的值 true。所有其它值将被丢弃.
示例
import * as Observable from "@daniel-nagy/transporter/Observable";
Observable.of(1, 2, 3)
.pipe(Observable.filter((num) => num % 2 === 0))
.subscribe(console.log);
第一个从
函数
function firstValueFrom<T>(observable: ObservableLike<T>): Promise<T>;
将可观测值转换成承诺,以可观测值释放的第一个值解决。 如果发现错误,承诺将被拒绝。 如果可观察者完成而未释放出价值,则承诺将被拒绝 EmptyError。 。 。 .
警告
如果被观察者不履行诺言 承诺永远不会实现.
示例
import * as Observable from "@daniel-nagy/transporter/Observable";
await Observable.firstValueFrom(Observable.of(1, 2, 3));
平面映射
函数
function flatMap<T, U>(
callback: (value: T) => ObservableLike<U> | PromiseLike<U>
): (observable: ObservableLike<T>) => Observable<U>;
调用每个可观测值的回调函数 。 回调函数返回一个被平分的新可观测值,以避免产生可观测值.
当源头和所有内在的可观测完成时,可观测完成.
示例
import * as Observable from "@daniel-nagy/transporter/Observable";
Observable.of(1, 2, 3).pipe(
Observable.flatMap((num) => Observable.of(num * 2))
);
地图
函数
function map<T, U>(
callback: (value: T) => U
): (observable: ObservableLike<T>) => Observable<U>;
调用可观测函数释放的每个值的回调函数,并释放回调函数返回的值.
示例
import * as Observable from "@daniel-nagy/transporter/Observable";
Observable.of(1, 2, 3).pipe(Observable.map((num) => num * 2));
合并
函数
function merge<T>(...observables: ObservableLike<T>[]): Observable<T>;
将2 或更多可观测到的合并为单个可观测的。 由此产生的可观测物要等所有可观测物完成后才能完成.
每个观测到的数值将按提供的顺序同步释放。 任何同步值都会按它们到达的顺序被放出.
示例
import * as Observable from "@daniel-nagy/transporter/Observable";
Observable.merge(Observable.of(1, 2, 3), Observable.of(4, 5, 6)).subscribe(
console.log
);
拿着
函数
function take(
amount: number
): <T>(observable: ObservableLike<T>) => Observable<T>;
第一个 n 的值,然后完成.
示例
import * as Observable from "@daniel-nagy/transporter/Observable";
Observable.of(1, 2, 3).pipe(Observable.take(2)).subscribe(console.log);
使用到结束
函数
function takeUntil(
signal: ObservableLike<unknown>
): <T>(observable: ObservableLike<T>) => Observable<T>;
从可观测到信号发射或完成的值.
示例
import * as Observable from "@daniel-nagy/transporter/Observable";
import * as Subject from "@daniel-nagy/transporter/Subject";
const signal = Subject.init();
Observable.cron(1000, () => Math.random()).pipe(Observable.takeUntil(signal));
setTimeout(() => signal.next(), 2000);
磁带
函数
function tap<T>(
callback: (value: T) => unknown
): <T>(observable: ObservableLike<T>) => Observable<T>;
允许当一个值被放出而不改变所放出值时执行效果 .
示例
import * as Observable from "@daniel-nagy/transporter/Observable";
Observable.of(1, 2, 3).pipe(Observable.tap(console.log)).subscribe();
超时
函数
function timeout<T>(
milliseconds: number,
callback?: (error: TimeoutError) => ObservableLike<T>
): <T>(observable: ObservableLike<T>) => Observable<T>;
如果某一数值未在规定的超时范围内出出,则导致可观察到的错误。 每次值被放出时,定时器都会重排 .
调用函数可能返回一个新的可观察到的来替换旧的或者返回特定的错误.
示例
import * as Observable from "@daniel-nagy/transporter/Observable";
Observable.cron(1000, () => Math.random())
.pipe(Observable.timeout(999))
.subscribe();
致观察员
函数
function toObserver<T>(
observerOrNext?: Observer<T> | ((value: T) => void)
): Observer<T>;
使用可能为观察员或函数的值并返回观察员。 如果调用没有参数, 它将会返回一个空对象 .
示例
import * as Observable from "@daniel-nagy/transporter/Observable";
const identity = (value) => value;
const observer = toObserver(identity);
代理服务器
模块
代理模块用于创建代理对象. 运输商会代用这些物体而不是克隆它们.
类型
构造器
职能
代理服务器
类型
type Proxy<T extends object> = JsObject.ReadonlyDeep<
JsObject.PickDeep<T, JsFunction.t | PubSub.t>
>;
A 类 Proxy 是一个只读的对象,其属性是函数.
从
构造器
function from<T extends object>(value: T): Proxy<T>;
从任意对象创建代理。 生成的对象将仅读取 函数将保留为属性.
示例
import * as Proxy from "@daniel-nagy/transporter/Proxy";
const proxy = Proxy.from({
a: "a",
b: async () => "👍",
c: [12, async () => "👌"]
});
// $ExpectType
// {
// readonly b: async () => "👍",
// readonly c: {
// readonly 1: async () => "👌"
// }
// }
异质
函数
function isProxy<T extends object, U>(value: Proxy<T> | U): value is Proxy<T>;
回返 true 如果对象是 Proxy。 。 。 .
示例
import * as Proxy from "@daniel-nagy/transporter/Proxy";
const proxy = Proxy.from({
b: async () => "👍"
});
Proxy.isProxy(proxy); // true
普贝
模块
PubSub模块用于包装可观测器,从而可用于pub/sub. A PubSub本质上是一个可观察的,谁订阅而不订阅的方法是同步的.
类型
构造器
阿辛克观察员
类型
type AsyncObserver<T> = {
next?(value: T): Promise<void>;
error?(error: unknown): Promise<void>;
complete?(): Promise<void>;
};
一个 Observer 谁的方法是同步的.
普贝
类型
interface PubSub<T> {
subscribe(
observerOrNext: AsyncObserver<T> | ((value: T) => Promise<void>)
): Promise<RemoteSubscription>;
}
一个 Observable 谁的订阅方法是同步的.
远程订阅
类型
type RemoteSubscription = {
unsubscribe(): Promise<void>;
};
A 类 Subscription 当未订阅时,它返回一个承诺.
从
构造器
function from<T>(observable: Observable.ObservableLike<T>): PubSub<T>;
将普通的可观测器变成同步的.
示例
import * as PubSub from "@daniel-nagy/transporter/PubSub";
const pubSub = PubSub.from(Observable.of(1, 2, 3));
会议
模块
会话模块用于创建客户端和服务器会话.
类型
常数
构造器
方法
探员
类型
type Agent = ClientAgent.t | ServerAgent.t;
一个 Agent 是一个管理单一资源并实现
运输员协议.
客户选项
类型
interface ClientOptions<DataType, Value> {
injector?: Injector.t;
protocol: Subprotocol<DataType, Value>;
resource: Resource<Value>;
}
创建 ClientSession。 。 。 .
客户会议
类型
class ClientSession<DataType, Value> extends Session<DataType, Value> {
createProxy(): Proxy.t<Value>;
}
A 类 ClientSession 在客户端上创建以代理远程资源.
资源
类型
interface Resource<Value> {}
A 类 Resource 是服务器提供的值.
服务器选项
类型
interface ServerOptions<DataType, Value> {
injector?: Injector.t;
protocol: Subprotocol<DataType, Value>;
provide: Value;
}
创建 ServerSession。 。 。 .
服务器会议
类型
class ServerSession<DataType, Value> extends Session<DataType, Value> {}
A 类 ServerSession 在服务器上创建以提供一个资源.
会议
类型
abstract class Session<DataType, Value> extends Supervisor.t<Agent> {
readonly injector?: Injector.t;
readonly input: Observable.Observer<Message.t<DataType>>;
readonly output: Observable.t<Message.t<DataType>>;
readonly protocol: Subprotocol<DataType, Value>;
}
A 类 Session 产卵和观察剂。 会话在活动时可能会生成多个服务器或客户端代理. 终止会话将终止会话所产生的所有仍在活化的物剂.
如果会话产生的所有物剂被终止,则会话自动被终止.
根监督员
常数
const rootSupervisor = Supervisor.init<Session>("RootSupervisor");
根上司观察所有活动会议.
资源
构造器
const Resource = <Value>(): Resource<Value>;
创建新 Resource。该容器类型是必要的,因为类型脚本
缺少对类型参数的部分推论.
import * as Session from "@daniel-nagy/transporter/Session";
import type { Api } from "...";
const resource = Session.Resource<Api>();
客户端
构造器
function client<DataType, Value>(
options: ClientOptions<DataType, Value>
): ClientSession<DataType, Value>;
创建新 ClientSession。 。 。 .
示例
import * as Session from "@daniel-nagy/transporter/Session";
import * as Subprotocol from "@daniel-nagy/transporter/Subprotocol";
import * as SuperJson from "@daniel-nagy/transporter/SuperJson";
import type { Api } from "...";
const httpProtocol = Subprotocol.init({
connectionMode: Subprotocol.ConnectionMode.ConnectionLess,
dataType: Subprotocol.DataType<SuperJson.t>(),
operationMode: Subprotocol.OperationMode.Unicast,
transmissionMode: Subprotocol.TransmissionMode.HalfDuplex
});
const session = Session.client({
protocol: httpProtocol,
resource: Session.Resource<Api>()
});
const client = session.createProxy();
服务器
构造器
function server<DataType, Value>(
options: ServerOptions<DataType, Value>
): ServerSession<DataType, Value>;
创建新 ServerSession。 。 。 .
示例
import * as Session from "@daniel-nagy/transporter/Session";
import * as Subprotocol from "@daniel-nagy/transporter/Subprotocol";
import * as SuperJson from "@daniel-nagy/transporter/SuperJson";
module User {
export async greet = () => "👋"
}
const httpProtocol = Subprotocol.init({
connectionMode: Subprotocol.ConnectionMode.ConnectionLess,
dataType: Subprotocol.DataType<SuperJson.t>(),
operationMode: Subprotocol.OperationMode.Unicast,
transmissionMode: Subprotocol.TransmissionMode.HalfDuplex
});
const session = Session.server({
protocol: httpProtocol,
provide: {
User
}
});
终止
方法
terminate(): void;
终止会话。 结束会话将完成输入和输出,并终止所有当前活动的代理.
议题
模块
A 类 Subject 可用于多播 Observable。 。 。 .
类型
构造器
方法
议题
类型
class Subject<T>
implements Observable.ObservableLike<T>, Observable.Observer<T> {}
A 类 Subject 两者都是 Observable 还有一个 Observer。 。 。 .
输入
构造器
function init<T>(): Subject<T>;
创建新 Subject。 。 。 .
示例
import * as Subject from "@daniel-nagy/transporter/Subject";
const subject = Subject.init<boolean>();
作为可观察
方法
asObservable(): Observable.t<T>;
将主题转换为热能观测.
完成
方法
complete(): void;
更改对象状态为 Complete。 。 。 .
错误
方法
error(error: unknown): void;
更改对象状态为 Error。 。 。 .
下一个
方法
next(value: T): void;
向所有订阅者输入此值 .
订阅
方法
subscribe(
observerOrNext?: Observable.Observer<T> | ((value: T) => void)
): Observable.Subscription;
订阅主题释放的状态变化和值 .
副议定书
模块
运算器协议是不可知的。 为了提供类型安全,需要一份次级议定书。 子议定书限制哪些类型可以包含在函数 IO. 例如,如果子议定书的数据类型是JSON,那么只有JSON的数据类型可以从远程函数输入或输出.
此外,如果满足了某些子议定书和网络条件,Transporter可以执行递归RPC. 递归RPC指函数或代理可以包含在函数IO中. 这是一个有趣的概念,因为它允许在调用堆栈上保持状态之间的状态. 例如,递归式RPC允许可观测器用于pub-sub.
要使用递归式RPC, 您的子协议必须是面向连接和双向的 。 如果这些条件得到满足,远程函数的调用签名将允许函数或代理作为输入或输出. 原来这些类型的连接在浏览器中很常见.
类型
构造器
职能
连接模式
类型
enum ConnectionMode {
/**
* A message can be sent from one endpoint to another without prior
* arrangement. For example, HTTP is a connectionless protocol.
*/
Connectionless = "Connectionless",
/**
* A session or connection is established before data can be transmitted. For
* example, TCP is a connection-oriented protocol.
*/
ConnectionOriented = "ConnectionOriented"
}
用于定义客户端和服务器之间的连接类型.
数据类型
类型
interface DataType<T> {}
将程序的输入和输出类型限制在特定的数据类型上.
操作模式
类型
enum OperationMode {
/**
* A single message is sent to every node in a network. This is a one-to-all
* transmission.
*/
Broadcast = "Broadcast",
/**
* A single message is sent to a subset of nodes in a network. This is a
* one-to-many transmission.
*/
Multicast = "Multicast",
/**
* A single message is sent to a single node. This is a one-to-one
* transmission.
*/
Unicast = "Unicast"
}
用于定义数据如何分配到网络中的节点.
副议定书
类型
interface Subprotocol<DataType, Input, Output> {}
用来限制函数输入和输出类型,以及确定是否可以启用递归RPC.
传输模式
类型
enum TransmissionMode {
/**
* Either side may transmit data at any time. This is a 2-way communication.
*/
Duplex = "Duplex",
/**
* Only one side can transmit data at a time. This is a 2-way communication.
*/
HalfDuplex = "HalfDuplex",
/**
* Only the sender can transmit data. This is a 1-way communication.
*/
Simplex = "Simplex"
}
用来定义数据如何通过网络传输.
数据类型
构造器
function DataType<const T>(): DataType<T>;
创建新 DataType。 。 。 .
示例
import * as Json from "@daniel-nagy/transporter/Json";
import * as Subprotocol from "@daniel-nagy/transporter/Subprotocol";
const jsonDataType = Subprotocol.DataType<Json.t>();
输入
构造器
function init(options: {
connectionMode: ConnectionMode;
dataType: DataType;
operationMode: OperationMode;
transmissionMode: TransmissionMode;
}): Subprotocol;
创建新 Subprotocol。 。 。 .
示例
import * as Subprotocol from "@daniel-nagy/transporter/Subprotocol";
import * as SuperJson from "@daniel-nagy/transporter/SuperJson";
const subprotocol = Subprotocol.init({
connectionMode: Session.ConnectionMode.ConnectionLess,
dataType: Subprotocol.DataType<SuperJson.t>(),
operationMode: Session.OperationMode.Unicast,
transmissionMode: Session.TransmissionMode.HalfDuplex
});
双向
函数
function isBidirectional(protocol: Subprotocol<unknown>): boolean;
回返 true 副议定书是双向的。 如果连接的操作模式是单向的,并且其传输模式是双向的或半双向的,则该连接被认为是双向的.
示例
import * as Subprotocol from "@daniel-nagy/transporter/Subprotocol";
import * as SuperJson from "@daniel-nagy/transporter/SuperJson";
const subprotocol = Subprotocol.init({
connectionMode: Session.ConnectionMode.ConnectionLess,
dataType: Subprotocol.DataType<SuperJson.t>(),
operationMode: Session.OperationMode.Unicast,
transmissionMode: Session.TransmissionMode.HalfDuplex
});
Subprotocol.isBidirectional(subprotocol); // true
超级杰森
模块
SuperJson模块将JSON扩展至包括许多内置的JavaScript类型,包括: Date, (中文(简体) ), RegExp, (中文(简体) ), Map(原始内容存档于2013-10-12)., ect.
类型
职能
超级杰森
类型
type SuperJson =
| void
| null
| undefined
| boolean
| number
| bigint
| string
| Date
| RegExp
| Array<SuperJson>
| Map<SuperJson, SuperJson>
| Set<SuperJson>
| { [key: string]: SuperJson };
一个扩展的JSON类型,包括了许多内建的JavaScript类型.
从杰森
函数
function fromJson(value: Json.t): SuperJson;
恢复编码 SuperJson 值来自 JSON 值.
示例
import * as SuperJson from "@daniel-nagy/transporter/SuperJson";
SuperJson.fromJson(value);
给杰森
函数
function toJson(value: SuperJson): Json.t;
编码 a SuperJson 值作为有效的 JSON 值.
示例
import * as SuperJson from "@daniel-nagy/transporter/SuperJson";
SuperJson.toJson(new Date());