Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Maybe async refactor #1287

Merged
merged 4 commits into from
Sep 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions packages/cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@

import * as Commands from "./commands";

import { executeMaybeAsyncFunction } from "@polywrap/core-js";
import { program } from "commander";

export const run = async (argv: string[]): Promise<void> => {
for (const command of Object.values(Commands)) {
if ("setup" in command) {
await executeMaybeAsyncFunction(command.setup, program);
await command.setup(program);
}
}

Expand Down
3 changes: 2 additions & 1 deletion packages/cli/src/commands/types.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { MaybeAsync } from "@polywrap/core-js";
import { Command as Program, Argument } from "commander";

export { Program, Argument };

export interface Command {
setup: (program: Program) => void;
setup: (program: Program) => MaybeAsync<void>;
}
6 changes: 1 addition & 5 deletions packages/cli/src/lib/option-parsers/client-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { intlMsg } from "../intl";
import { importTypescriptModule } from "../system";
import { getTestEnvClientConfig } from "../test-env";

import { executeMaybeAsyncFunction } from "@polywrap/core-js";
import { PolywrapClientConfig } from "@polywrap/client-js";
import path from "path";

Expand Down Expand Up @@ -43,10 +42,7 @@ export async function parseClientConfigOption(
process.exit(1);
}

finalClientConfig = await executeMaybeAsyncFunction(
configModule.getClientConfig,
finalClientConfig
);
finalClientConfig = await configModule.getClientConfig(finalClientConfig);

try {
validateClientConfig(finalClientConfig);
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/src/lib/workflow/JobRunner.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { JobResult, JobStatus, Step } from "./types";

import { PolywrapClient } from "@polywrap/client-js";
import { executeMaybeAsyncFunction, MaybeAsync } from "@polywrap/core-js";
import { MaybeAsync } from "@polywrap/core-js";
import { WorkflowJobs } from "@polywrap/polywrap-manifest-types-js";
import { ClientConfigBuilder } from "@polywrap/client-config-builder-js";

Expand Down Expand Up @@ -208,7 +208,7 @@ export class JobRunner {
this.jobOutput.set(absId, result);

if (this.onExecution) {
await executeMaybeAsyncFunction(this.onExecution, absId, result);
await this.onExecution(absId, result);
}
}
}
Expand Down
41 changes: 21 additions & 20 deletions packages/js/core/src/__tests__/MaybeAsync.spec.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,41 @@
import {
MaybeAsync,
executeMaybeAsyncFunction,
isPromise,
} from "..";
import { MaybeAsync, isPromise } from "..";

class ClassInstance {
interface IClassInterface {
normalMethod(arg: string): MaybeAsync<string>;
asyncMethod(arg: string): MaybeAsync<string>;
}

class ClassInstance implements IClassInterface {
constructor(private _prop: string) {}

normalMethod(arg: string): string {
return this._prop + arg;
}

async asyncMethod(arg: string): Promise<string> {
await new Promise((resolve) =>
setTimeout(resolve, 200)
);
await new Promise((resolve) => setTimeout(resolve, 200));

return this._prop + arg;
}
}

describe("MaybeAsync", () => {
const promise: MaybeAsync<string> =
new Promise<string>((resolve, reject) => { return "" });
const testFunction = (args: unknown[]) => { return "foo" };
const testFunctionReturnPromise = (args: unknown[]) => new Promise<string>((resolve) => { resolve("foo") });
const testFunction = (): MaybeAsync<string> => {
return "foo";
};
const testFunctionReturnPromise = (): MaybeAsync<string> =>
new Promise<string>((resolve) => {
resolve("foo");
});

it("sanity", async () => {
expect(isPromise(promise)).toBe(true);
expect(await executeMaybeAsyncFunction(testFunction)).toBe("foo");
expect(await executeMaybeAsyncFunction(testFunctionReturnPromise)).toBe("foo");
expect(await testFunction()).toBe("foo");
expect(await testFunctionReturnPromise()).toBe("foo");
});

it("works with class instances", async () => {
const instance = new ClassInstance("bar");
expect(await executeMaybeAsyncFunction(instance.normalMethod.bind(instance, "foo"))).toBe("barfoo")
expect(await executeMaybeAsyncFunction(instance.asyncMethod.bind(instance, "foo"))).toBe("barfoo")
})
const instance: IClassInterface = new ClassInstance("bar");
expect(await instance.normalMethod("foo")).toBe("barfoo");
expect(await instance.asyncMethod("foo")).toBe("barfoo");
});
});
17 changes: 0 additions & 17 deletions packages/js/core/src/types/MaybeAsync.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1 @@
export type MaybeAsync<T> = Promise<T> | T;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh wow, had no clue you could await a non-async function and it'd return just fine.


export const isPromise = <T extends unknown>(
test?: MaybeAsync<T>
): test is Promise<T> =>
!!test && typeof (test as Promise<T>).then === "function";

// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types
export const executeMaybeAsyncFunction = async <T extends unknown>(
func: (...args: unknown[]) => Promise<T> | T,
...args: unknown[]
): Promise<T> => {
let result = func(...args);
if (isPromise(result)) {
result = await result;
}
return result;
};
9 changes: 4 additions & 5 deletions packages/js/core/src/types/Plugin.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/naming-convention */
import { Client, MaybeAsync, executeMaybeAsyncFunction } from ".";
import { Client, MaybeAsync } from ".";

import { WrapManifest } from "@polywrap/wrap-manifest-types-js";
import { Result, ResultErr, ResultOk } from "@polywrap/result";
Expand Down Expand Up @@ -60,9 +60,8 @@ export abstract class PluginModule<
);
}

const data = await executeMaybeAsyncFunction<TResult>(
fn.bind(this, args, client)
);
const data = await fn(args, client);

return ResultOk(data);
}

Expand All @@ -77,7 +76,7 @@ export abstract class PluginModule<
PluginMethod<TArgs, TResult>
>)[method];

return fn;
return fn.bind(this);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ import {
IUriResolver,
Uri,
Client,
executeMaybeAsyncFunction,
Wrapper,
IUriResolutionContext,
UriPackageOrWrapper,
UriResolutionResult,
Expand Down Expand Up @@ -39,9 +37,7 @@ export class PackageToWrapperCacheResolver implements IUriResolver<Error> {
client: Client,
resolutionContext: IUriResolutionContext
): Promise<Result<UriPackageOrWrapper, Error>> {
const wrapper = await executeMaybeAsyncFunction<Wrapper | undefined>(
this.cache.get.bind(this.cache, uri)
);
const wrapper = await this.cache.get(uri);

if (wrapper) {
const result = UriResolutionResult.ok(uri, wrapper);
Expand Down Expand Up @@ -78,9 +74,7 @@ export class PackageToWrapperCacheResolver implements IUriResolver<Error> {
const wrapper = createResult.value;

for (const uri of resolutionPath) {
await executeMaybeAsyncFunction<Wrapper | undefined>(
this.cache.set.bind(this.cache, uri, wrapper)
);
await this.cache.set(uri, wrapper);
}

result = UriResolutionResult.ok(result.value.uri, wrapper);
Expand All @@ -89,9 +83,7 @@ export class PackageToWrapperCacheResolver implements IUriResolver<Error> {
const resolutionPath: Uri[] = subContext.getResolutionPath();

for (const uri of resolutionPath) {
await executeMaybeAsyncFunction<Wrapper | undefined>(
this.cache.set.bind(this.cache, uri, wrapper)
);
await this.cache.set(uri, wrapper);
}
}
}
Expand Down
Loading