Skip to content

Commit

Permalink
0.1.26 more better
Browse files Browse the repository at this point in the history
  • Loading branch information
rvdende committed Jun 3, 2024
1 parent a97c245 commit 617fb12
Show file tree
Hide file tree
Showing 11 changed files with 98 additions and 249 deletions.
2 changes: 1 addition & 1 deletion jsr.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "@netron/surreal",
"version": "0.1.25",
"version": "0.1.26",
"exports": "./index.ts"
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@netron/surreal",
"version": "0.1.25",
"version": "0.1.26",
"description": "type safe surrealdb",
"main": "index.ts",
"scripts": {
Expand Down
61 changes: 34 additions & 27 deletions src/NSurreal.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,26 @@
import { ConnectionOptions, Surreal } from "surrealdb.js";
import { generate_unique_hash_repeatably } from "./hash";
import jsonToZod from "json-to-zod";
import { type ConnectionOptions, Surreal } from "surrealdb.js";
import fs from "fs";
import JsonToTS from "./jsontots";

/** TypeSafe SurrealDB Client https://jsr.io/@netron/surreal based on surrealdb.js
* See https://surrealdb.com/docs/surrealdb/integration/sdks/javascript */
export class NSurreal<G extends Record<string, object> = {}> {
export class NSurreal<G extends Record<string, object>> {
client: Surreal;
timer: NodeJS.Timeout;
timestamp_connected: Date | undefined;
url: string | undefined;
opts: ConnectionOptions | undefined;
output_path: string = "./src/generated";
output_path = "./src/generated";

debug = false;

constructor(options?: { output_path?: string; debug?: boolean }) {
skip_write = false;

constructor(options?: {
output_path?: string;
debug?: boolean;
skip_write?: boolean;
}) {
if (options?.output_path) {
this.output_path = options.output_path;
}
Expand All @@ -25,15 +29,19 @@ export class NSurreal<G extends Record<string, object> = {}> {
this.debug = options.debug;
}

if (options?.skip_write) {
this.skip_write = options.skip_write;
}

this.client = new Surreal();
this.timer = setInterval(() => {
if (!this.timestamp_connected) return;
const diff = new Date().getTime() - this.timestamp_connected!.getTime();
const diff = new Date().getTime() - this.timestamp_connected.getTime();
if (diff > 1000 * 60) {
if (this.client) {
this.client.close();
this.client.close().catch(console.error);
}
this.connect(this.url!, this.opts!);
this.connect(this.url!, this.opts).catch(console.error);
}
}, 10000);
}
Expand All @@ -42,7 +50,7 @@ export class NSurreal<G extends Record<string, object> = {}> {
* https://surrealdb.com/docs/surrealdb/integration/sdks/javascript#connect
*/

log(...input: any[]) {
log(...input: Parameters<typeof console.log>) {
if (this.debug) console.log(`NSurreal -`, input);
}

Expand Down Expand Up @@ -97,7 +105,7 @@ export class NSurreal<G extends Record<string, object> = {}> {
const uid = uniqueID as string;

// ensure uniqueId starts with capital.
if (uid[0] != uid[0].toUpperCase()) {
if (!uid.startsWith(uid.at(0)?.toUpperCase() ?? "")) {
throw new Error("uniqueID must start with a capital letter.");
}

Expand All @@ -115,7 +123,7 @@ export class NSurreal<G extends Record<string, object> = {}> {

this.log("Query result", result);

if (uniqueID) {
if (uniqueID && !this.skip_write) {
const uid = uniqueID as string;

let querycount = query.split(";").length;
Expand All @@ -125,7 +133,7 @@ export class NSurreal<G extends Record<string, object> = {}> {

this.log(`Query count: ${querycount}`);

let responseobj: Record<string, (typeof result)[number]> = {};
const responseobj: Record<string, (typeof result)[number]> = {};

result.forEach((i, idx) => {
responseobj[`${uid}_query${idx + 1}`] = i;
Expand All @@ -152,15 +160,15 @@ export class NSurreal<G extends Record<string, object> = {}> {
this.log("Error creating directory", err);
});

let outputtype = ts.map((i, idx) => {
const outputtype = ts.map((i, idx) => {
if (idx == 0) {
let output = i.split("\n").at(0)?.replace("{", "[");
output += "\n";
// change object to tuple..
output += i
.split("\n")
.slice(1, -1)
.map((x) => x.split(":")[1].slice(0, -1))
.map((x) => x.split(":").at(1)?.slice(0, -1))
.join(",\n");

output += "\n";
Expand All @@ -177,29 +185,28 @@ export class NSurreal<G extends Record<string, object> = {}> {
await fs.promises
.writeFile(
`${this.output_path}/querytypes/${uid}.ts`,
`import { RecordId } from "surrealdb.js";
`import type { UUID, RecordId } from "surrealdb.js";
export ${outputtype.join("\n")}`
)
.catch((err) => {
this.log("Error writing to file", err);
});

let schemas = await this.read_querytypes();
const schemas = await this.read_querytypes();

await fs.promises.writeFile(
`${this.output_path}/combined.ts`,
`import { z } from "zod";\n
${schemas
.map((i) => {
return `import { ${i.replace(".ts", "")} } from "./querytypes/${i.replace(
".ts",
""
)}";`;
})
.join("\n")}
`${schemas
.map((i) => {
return `import type { ${i.replace(
".ts",
""
)} } from "./querytypes/${i.replace(".ts", "")}";`;
})
.join("\n")}
export type Queries = {\n${schemas
.map((i) => ` "${i.replace(".ts", "")}": ${i.replace(".ts", "")}`)
.map((i) => ` ${i.replace(".ts", "")}: ${i.replace(".ts", "")};`)
.join("\n")}\n}`
);
}
Expand Down
39 changes: 0 additions & 39 deletions src/generateschema.ts

This file was deleted.

16 changes: 0 additions & 16 deletions src/hash.ts

This file was deleted.

25 changes: 12 additions & 13 deletions src/jsontots/get-names.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
// import * as pluralize from "pluralize";

import {
TypeStructure,
NameEntry,
NameStructure,
type TypeStructure,
type NameEntry,
type NameStructure,
TypeGroup,
TypeDescription,
type TypeDescription,
} from "./model";
import {
getTypeDescriptionGroup,
Expand Down Expand Up @@ -71,7 +71,7 @@ function getName(

export function getNames(
typeStructure: TypeStructure,
rootName: string = "RootObject"
rootName = "RootObject"
): NameEntry[] {
return getName(typeStructure, rootName, [], false).names.reverse();
}
Expand All @@ -83,7 +83,7 @@ function getNameById(
types: TypeDescription[],
nameMap: NameEntry[]
): string {
let nameEntry = nameMap.find((_) => _.id === id);
const nameEntry = nameMap.find((_) => _.id === id);

if (nameEntry) {
return nameEntry.name;
Expand All @@ -109,7 +109,6 @@ function getNameById(
.map((key) => parseKeyMetaData(key).keyValue)
// .map((name) => (isInsideArray ? pluralize.singular(name) : name))
.map(pascalCase)
// @ts-ignore
.map(normalizeInvalidTypeName)
.map(pascalCase) // needed because removed symbols might leave first character uncapitalized
.map((name) =>
Expand All @@ -122,7 +121,7 @@ function getNameById(
break;
}

nameMap.push({ id, name: name as string });
nameMap.push({ id, name: String(name) });

if (!name) {
throw new Error("could not getNameById");
Expand All @@ -147,11 +146,11 @@ function capitalize(name: string) {
return name.charAt(0).toUpperCase() + name.slice(1);
}

function normalizeInvalidTypeName(name: string): string {
if (/^[a-zA-Z][a-zA-Z0-9]*$/.test(name)) {
return name;
function normalizeInvalidTypeName(name: string | null): string {
if (/^[a-zA-Z][a-zA-Z0-9]*$/.test(name ?? "null")) {
return String(name);
} else {
const noSymbolsName = name.replace(/[^a-zA-Z0-9]/g, "");
const noSymbolsName = String(name ?? "null").replace(/[^a-zA-Z0-9]/g, "");
const startsWithWordCharacter = /^[a-zA-Z]/.test(noSymbolsName);
return startsWithWordCharacter ? noSymbolsName : `_${noSymbolsName}`;
}
Expand All @@ -176,7 +175,7 @@ function getArrayName(
return "any";
} else if (typeDesc.arrayOfTypes!.length === 1) {
const [idOrPrimitive] = typeDesc.arrayOfTypes!;
return convertToReadableType(idOrPrimitive, types, nameMap);
return convertToReadableType(idOrPrimitive!, types, nameMap);
} else {
return unionToString(typeDesc, types, nameMap);
}
Expand Down
Loading

0 comments on commit 617fb12

Please sign in to comment.