Force return types to be specified

Makes it easier to use the library. Best to enforce this early on.
This commit is contained in:
Franck Royer 2021-05-03 15:52:38 +10:00
parent 3c8a63cfcd
commit 9e30627e2b
No known key found for this signature in database
GPG Key ID: A82ED75A8DFC50A4
11 changed files with 51 additions and 41 deletions

View File

@ -15,6 +15,7 @@
],
"globals": { "BigInt": true, "console": true, "WebAssembly": true },
"rules": {
"@typescript-eslint/explicit-function-return-type": ["error"],
"@typescript-eslint/explicit-module-boundary-types": "off",
"eslint-comments/disable-enable-pair": [
"error",

View File

@ -13,7 +13,7 @@ import { ChatMessage } from './chat_message';
const ChatContentTopic = 'dingpu';
(async function () {
(async function (): Promise<void> {
const opts = processArguments();
const waku = await Waku.create({
@ -124,7 +124,7 @@ function processArguments(): Options {
return opts;
}
function printMessage(chatMsg: ChatMessage) {
function printMessage(chatMsg: ChatMessage): void {
const timestamp = chatMsg.timestamp.toLocaleString([], {
month: 'short',
day: 'numeric',

View File

@ -1,3 +1,3 @@
export function delay(ms: number) {
export function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}

View File

@ -98,16 +98,21 @@ export default class Waku {
* Dials to the provided peer.
* @param peer The peer to dial
*/
async dial(peer: PeerId | Multiaddr | string) {
await this.libp2p.dialProtocol(peer, [RelayCodec, StoreCodec]);
async dial(
peer: PeerId | Multiaddr | string
): Promise<{
stream: import('libp2p-interfaces/src/stream-muxer/types').MuxedStream;
protocol: string;
}> {
return this.libp2p.dialProtocol(peer, [RelayCodec, StoreCodec]);
}
addPeerToAddressBook(peerId: PeerId, multiaddr: Multiaddr[]) {
addPeerToAddressBook(peerId: PeerId, multiaddr: Multiaddr[]): void {
this.libp2p.peerStore.addressBook.set(peerId, multiaddr);
}
async stop() {
await this.libp2p.stop();
async stop(): Promise<void> {
return this.libp2p.stop();
}
/**

View File

@ -18,7 +18,7 @@ export function getRelayPeers(
router: Gossipsub,
topic: string,
count: number,
filter: (id: string) => boolean = () => true
filter: (id: string) => boolean = (): boolean => true
): Set<string> {
const peersInTopic = router.topics.get(topic);
if (!peersInTopic) {

View File

@ -32,10 +32,7 @@ describe('Waku Relay', () => {
}),
]);
await waku1.addPeerToAddressBook(
waku2.libp2p.peerId,
waku2.libp2p.multiaddrs
);
waku1.addPeerToAddressBook(waku2.libp2p.peerId, waku2.libp2p.multiaddrs);
await Promise.all([
new Promise((resolve) =>
@ -133,7 +130,7 @@ describe('Waku Relay', () => {
await waku.relay.send(message);
let msgs = [];
let msgs: WakuMessage[] = [];
while (msgs.length === 0) {
await delay(200);
@ -143,7 +140,7 @@ describe('Waku Relay', () => {
expect(msgs[0].contentTopic).to.equal(message.contentTopic);
expect(msgs[0].version).to.equal(message.version);
const payload = Buffer.from(msgs[0].payload);
const payload = Buffer.from(msgs[0].payload!);
expect(Buffer.compare(payload, message.payload!)).to.equal(0);
});
@ -216,7 +213,7 @@ describe('Waku Relay', () => {
await delay(1000);
await waku.relay.send(message);
let msgs = [];
let msgs: WakuMessage[] = [];
while (msgs.length === 0) {
console.log('Waiting for messages');
@ -227,7 +224,7 @@ describe('Waku Relay', () => {
expect(msgs[0].contentTopic).to.equal(message.contentTopic);
expect(msgs[0].version).to.equal(message.version);
const payload = Buffer.from(msgs[0].payload);
const payload = Buffer.from(msgs[0].payload!);
expect(Buffer.compare(payload, message.payload!)).to.equal(0);
});

View File

@ -78,7 +78,7 @@ export class WakuRelay extends Gossipsub {
* @override
* @returns {void}
*/
start() {
start(): void {
super.start();
super.subscribe(constants.RelayDefaultTopic);
}
@ -89,7 +89,7 @@ export class WakuRelay extends Gossipsub {
* @param {WakuMessage} message
* @returns {Promise<void>}
*/
async send(message: WakuMessage) {
async send(message: WakuMessage): Promise<void> {
const msg = message.encode();
await super.publish(constants.RelayDefaultTopic, Buffer.from(msg));
}

View File

@ -31,10 +31,10 @@ export class RelayHeartbeat extends Heartbeat {
this._heartbeatTimer = {
_intervalId: undefined,
runPeriodically: (fn, period) => {
runPeriodically: (fn, period): void => {
this._heartbeatTimer!._intervalId = setInterval(fn, period);
},
cancel: () => {
cancel: (): void => {
clearTimeout(timeout);
clearInterval(this._heartbeatTimer?._intervalId as NodeJS.Timeout);
},

View File

@ -2,14 +2,14 @@ import fs, { promises as asyncFs } from 'fs';
import { promisify } from 'util';
import { delay } from '../lib/delay';
export const existsAsync = (filepath: string) =>
export const existsAsync = (filepath: string): Promise<void> =>
asyncFs.access(filepath, fs.constants.F_OK);
export const openAsync = promisify(fs.open);
export const mkdirAsync = asyncFs.mkdir;
export async function waitForFile(path: string) {
export async function waitForFile(path: string): Promise<void> {
let found = false;
do {
try {

View File

@ -4,7 +4,10 @@ import { Tail } from 'tail';
import { waitForFile } from './async_fs';
export default async function waitForLine(filepath: string, logLine: string) {
export default async function waitForLine(
filepath: string,
logLine: string
): Promise<void> {
await pTimeout(waitForFile(filepath), 2000);
const options = {
@ -22,7 +25,7 @@ export default async function waitForLine(filepath: string, logLine: string) {
tail.unwatch();
}
async function find(tail: Tail, line: string) {
async function find(tail: Tail, line: string): Promise<string> {
return new Promise((resolve, reject) => {
tail.on('line', (data: string) => {
if (data.includes(line)) {

View File

@ -58,7 +58,7 @@ export class NimWaku {
this.logPath = `${LOG_DIR}/nim-waku_${logName}.log`;
}
async start(args?: Args) {
async start(args?: Args): Promise<void> {
try {
await existsAsync(LOG_DIR);
} catch (e) {
@ -116,7 +116,7 @@ export class NimWaku {
await this.waitForLog('RPC Server started');
}
public stop() {
public stop(): void {
dbg(
`nim-waku ${
this.process ? this.process.pid : this.pid
@ -126,7 +126,7 @@ export class NimWaku {
this.process = undefined;
}
async waitForLog(msg: string) {
async waitForLog(msg: string): Promise<void> {
return waitForLine(this.logPath, msg);
}
@ -134,10 +134,10 @@ export class NimWaku {
* for known peers
* @throws if nim-waku2 isn't started.
*/
async peers() {
async peers(): Promise<string[]> {
this.checkProcess();
const res = await this.rpcCall('get_waku_v2_admin_v1_peers', []);
const res = await this.rpcCall<string[]>('get_waku_v2_admin_v1_peers', []);
return res.result;
}
@ -145,12 +145,15 @@ export class NimWaku {
async info(): Promise<RpcInfoResponse> {
this.checkProcess();
const res = await this.rpcCall('get_waku_v2_debug_v1_info', []);
const res = await this.rpcCall<RpcInfoResponse>(
'get_waku_v2_debug_v1_info',
[]
);
return res.result;
}
async sendMessage(message: WakuMessage) {
async sendMessage(message: WakuMessage): Promise<boolean> {
this.checkProcess();
if (!message.payload) {
@ -162,7 +165,7 @@ export class NimWaku {
contentTopic: message.contentTopic,
};
const res = await this.rpcCall('post_waku_v2_relay_v1_message', [
const res = await this.rpcCall<boolean>('post_waku_v2_relay_v1_message', [
RelayDefaultTopic,
rpcMessage,
]);
@ -170,12 +173,13 @@ export class NimWaku {
return res.result;
}
async messages() {
async messages(): Promise<WakuMessage[]> {
this.checkProcess();
const res = await this.rpcCall('get_waku_v2_relay_v1_messages', [
RelayDefaultTopic,
]);
const res = await this.rpcCall<WakuMessage[]>(
'get_waku_v2_relay_v1_messages',
[RelayDefaultTopic]
);
return res.result;
}
@ -213,10 +217,10 @@ export class NimWaku {
return `http://localhost:${port}/`;
}
private async rpcCall(
private async rpcCall<T>(
method: string,
params: Array<string | number | unknown>
) {
): Promise<{ result: T }> {
const res = await axios.post(
this.rpcUrl,
{
@ -233,7 +237,7 @@ export class NimWaku {
return res.data;
}
private checkProcess() {
private checkProcess(): void {
if (!this.process) {
throw "Nim Waku isn't started";
}
@ -282,7 +286,7 @@ export function strToHex(str: string): string {
return hex;
}
export function bufToHex(buffer: Uint8Array) {
export function bufToHex(buffer: Uint8Array): string {
return Array.prototype.map
.call(buffer, (x) => ('00' + x.toString(16)).slice(-2))
.join('');