Skip to content

Commit

Permalink
added type on websocket param return type
Browse files Browse the repository at this point in the history
  • Loading branch information
soya-miruku committed Nov 23, 2023
1 parent 78d9a66 commit a93f72c
Show file tree
Hide file tree
Showing 6 changed files with 57 additions and 21 deletions.
1 change: 1 addition & 0 deletions compile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ await build({
"ws": "^8.13.0",
},
devDependencies: {
"esbuild": "latest",
"@types/node": "^18.7.18",
"@types/ws": "8.5.3",
"type-fest": "latest"
Expand Down
2 changes: 1 addition & 1 deletion project.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"name": "@soyamiruku/typed-surql",
"version": "0.0.2"
"version": "1.0.15"
}
10 changes: 5 additions & 5 deletions src/client.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import "npm:reflect-metadata@latest";

import { Class, Constructor } from "npm:type-fest@latest";
import { Class, Constructor } from "npm:type-fest";
import { IFieldParams, ITable, Idx } from "./decerators.ts";
import { AsBasicModel, CreateInput, IModel, LengthGreaterThanOne, ModelKeysDot, OnlyFields, TransformSelected, UnionToArray } from "./types.ts";
import { STRATEGY, TypedSurQL } from "./index.ts";
import { TypedSurQL } from "./index.ts";
import { Surreal } from "https://deno.land/x/surrealdb/mod.ts";
import { field, val, ql, SQLType, Instance, FnBody, queryModel } from "./query.ts";
import { ActionResult, LiveQueryResponse, Patch } from "./surreal-types.ts";
Expand Down Expand Up @@ -85,7 +85,7 @@ export class Model implements IModel {

public static async live<SubModel extends Model>(this: { new(): SubModel }, callback?: (data: LiveQueryResponse<OnlyFields<SubModel>>) => unknown, diff?: boolean): Promise<string> {
const instance = new this();
if (STRATEGY === "HTTP") throw new Error("Live queries are not supported in HTTP mode");
if (TypedSurQL.STRATEGY === "HTTP") throw new Error("Live queries are not supported in HTTP mode");
return (TypedSurQL.SurrealDB as Surreal).live<Record<string, OnlyFields<SubModel>>>(instance.tableName, callback as any, diff);
}

Expand Down Expand Up @@ -180,7 +180,7 @@ export class Model implements IModel {
if (!transformedData) {
throw new Error("transformedData is undefined");
}
if (STRATEGY === "HTTP") {
if (TypedSurQL.STRATEGY === "HTTP") {
if (Array.isArray(transformedData)) {
if (!transformedData.length) return [];
return await TypedSurQL.SurrealDB.query(`INSERT INTO ${instance.tableName} ${JSON.stringify(transformedData)}`)
Expand All @@ -204,7 +204,7 @@ export class Model implements IModel {

public static async patch<SubModel extends Model>(this: { new(): SubModel }, data?: Patch[] | undefined): Promise<Patch[]> {
const instance = new this();
if (STRATEGY === "HTTP") throw new Error("Patch queries are not supported in HTTP mode")
if (TypedSurQL.STRATEGY === "HTTP") throw new Error("Patch queries are not supported in HTTP mode")
return await (TypedSurQL.SurrealDB as Surreal).patch(instance.tableName, data);
}

Expand Down
61 changes: 48 additions & 13 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,60 @@
import "npm:reflect-metadata@latest";
import "npm:core-js@latest";
import { ExperimentalSurrealHTTP, Surreal } from "https://deno.land/x/surrealdb/mod.ts";
import { AsyncReturnType } from "npm:type-fest@latest";
import { AsyncReturnType } from "npm:type-fest";
import { ConnectionOptions } from "./surreal-types.ts";

export let STRATEGY: "HTTP" | "WS" = "HTTP";
export type StrategyType = "HTTP" | "WS";
export type SurrealClient = AsyncReturnType<typeof TypedSurQL['Init']>;
export type SurrealStratClient<Strategy extends StrategyType = "WS"> = Strategy extends "WS" ? Surreal : ExperimentalSurrealHTTP;

export class TypedSurQL {
export class TypedSurQL<Strategy extends StrategyType = "WS"> {
public static SurrealDB: Surreal;
public static STRATEGY: StrategyType = "WS";

public static Init(url: string, opts?: ConnectionOptions & { websocket?: boolean }) {
if (!url) throw new Error("URL is required");
if (opts?.websocket === undefined || opts?.websocket === true)
STRATEGY = "WS";
constructor(public readonly SurrealDB: SurrealStratClient<Strategy>) { }

return new Promise<Surreal | ExperimentalSurrealHTTP>((resolve, reject) => {
const db = STRATEGY === "WS" ? new Surreal() : new ExperimentalSurrealHTTP();
public static Init<Strategy extends boolean>(url: string, opts?: ConnectionOptions & { websocket?: Strategy }) {
if (!url) throw new Error("URL is required");
this.SetStrategy(opts?.websocket);
return new Promise<SurrealStratClient<Strategy extends true ? "WS" : "HTTP">>((resolve, reject) => {
const db = TypedSurQL.STRATEGY === "WS" ? new Surreal() : new ExperimentalSurrealHTTP();
try {
void db.connect(url, opts as any).then(() => {
TypedSurQL.SurrealDB = db as Surreal;
resolve(db)
resolve(db as SurrealStratClient<Strategy extends true ? "WS" : "HTTP">)
});
} catch (e) {
reject(e)
}
})
}

public promisify() {
return new Promise<SurrealStratClient<Strategy>>((resolve, reject) => {
try {
resolve(this.SurrealDB)
} catch (e) {
reject(e)
}
})
}

public static SetStrategy<Strategy extends boolean = true>(strategy?: Strategy) {
if (strategy === undefined || strategy === true)
this.STRATEGY = "WS";
else this.STRATEGY = "HTTP";
}

public static Create<Strategy extends boolean>(url: string, opts?: ConnectionOptions & { websocket?: Strategy }) {
if (!url) throw new Error("URL is required");
this.SetStrategy(opts?.websocket);

return new Promise<TypedSurQL<Strategy extends true ? "WS" : "HTTP">>((resolve, reject) => {
const db = this.STRATEGY === "WS" ? new Surreal() : new ExperimentalSurrealHTTP();
try {
void db.connect(url, opts as any).then(() => {
resolve(new TypedSurQL(db as SurrealStratClient<Strategy extends true ? "WS" : "HTTP">))
});
} catch (e) {
reject(e)
Expand All @@ -30,14 +65,14 @@ export class TypedSurQL {
public static async Wait(iterations = 5): Promise<boolean> {
if (iterations === 0) return false;
if (!TypedSurQL.SurrealDB) {
await new Promise((resolve) => setTimeout(resolve, 100));
await new Promise((resolve) => setTimeout(resolve, 150));
return TypedSurQL.Wait(iterations - 1);
}
return await TypedSurQL.SurrealDB.wait().then(() => true);
return true;
// return await TypedSurQL.SurrealDB.wait().then(() => true);
}
}

export type SurrealClient = AsyncReturnType<typeof TypedSurQL['Init']>;

export * from "./decerators.ts";
export type * from "./types.ts";
Expand Down
2 changes: 1 addition & 1 deletion src/query.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Constructor, Simplify } from "npm:type-fest@latest";
import { Constructor, Simplify } from "npm:type-fest";
import { qlFn } from "./functions/index.ts";
import { DotNestedKeys, IModel, OnlyFields } from "./types.ts";
import { alias, arrays, count, cryptos, durations, http, math, meta, operations, parse, rands, search, session, strings, time } from "./functions/mod.ts";
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ConditionalExcept, ConditionalPick, ConditionalPickDeepOptions, EmptyObject, Except, IsEqual, Merge, ReadonlyKeysOf, Simplify, UnknownRecord } from "npm:type-fest@latest";
import { ConditionalExcept, ConditionalPick, ConditionalPickDeepOptions, EmptyObject, Except, IsEqual, Merge, ReadonlyKeysOf, Simplify, UnknownRecord } from "npm:type-fest";

/**
Simplifies a type while including and/or excluding certain types from being simplified. Useful to improve type hints shown in editors. And also to transform an interface into a type to aide with assignability.
Expand Down

0 comments on commit a93f72c

Please sign in to comment.