mirror of
https://github.com/shishantbiswas/bknd.git
synced 2026-03-16 12:37:20 +00:00
* changed tb imports * cleanup: replace console.log/warn with $console, remove commented-out code Removed various commented-out code and replaced direct `console.log` and `console.warn` usage across the codebase with `$console` from "core" for standardized logging. Also adjusted linting rules in biome.json to enable warnings for `console.log` usage. * ts: enable incremental * fix imports in test files reorganize imports to use "@sinclair/typebox" directly, replacing local utility references, and add missing "override" keywords in test classes. * added media permissions (#142) * added permissions support for media module introduced `MediaPermissions` for fine-grained access control in the media module, updated routes to enforce these permissions, and adjusted permission registration logic. * fix: handle token absence in getUploadHeaders and add tests for transport modes ensure getUploadHeaders does not set Authorization header when token is missing. Add unit tests to validate behavior for different token_transport options. * remove console.log on DropzoneContainer.tsx Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * add bcrypt and refactored auth resolve (#147) * reworked auth architecture with improved password handling and claims Refactored password strategy to prepare supporting bcrypt, improving hashing/encryption flexibility. Updated authentication flow with enhanced user resolution mechanisms, safe JWT generation, and consistent profile handling. Adjusted dependencies to include bcryptjs and updated lock files accordingly. * fix strategy forms handling, add register route and hidden fields Refactored strategy forms to include hidden fields for type and name. Added a registration route with necessary adjustments to the admin controller and routes. Corrected field handling within relevant forms and components. * refactored auth handling to support bcrypt, extracted user pool * update email regex to allow '+' and '_' characters * update test stub password for AppAuth spec * update data exceptions to use HttpStatus constants, adjust logging level in AppUserPool * rework strategies to extend a base class instead of interface * added simple bcrypt test * add validation logs and improve data validation handling (#157) Added warning logs for invalid data during mutator validation, refined field validation logic to handle undefined values, and adjusted event validation comments for clarity. Minor improvements include exporting events from core and handling optional chaining in entity field validation. * modify MediaApi to support custom fetch implementation, defaults to native fetch (#158) * modify MediaApi to support custom fetch implementation, defaults to native fetch added an optional `fetcher` parameter to allow usage of a custom fetch function in both `upload` and `fetcher` methods. Defaults to the standard `fetch` if none is provided. * fix tests and improve api fetcher types * update admin basepath handling and window context integration (#155) Refactored `useBkndWindowContext` to include `admin_basepath` and updated its usage in routing. Improved type consistency with `AdminBkndWindowContext` and ensured default values are applied for window context. * trigger `repository-find-[one|many]-[before|after]` based on `limit` (#160) * refactor error handling in authenticator and password strategy (#161) made `respondWithError` method public, updated login and register routes in `PasswordStrategy` to handle errors using `respondWithError` for consistency. * add disableSubmitOnError prop to NativeForm and export getFlashMessage (#162) Introduced a `disableSubmitOnError` prop to NativeForm to control submit button behavior when errors are present. Also exported `getFlashMessage` from the core for external usage. * update dependencies in package.json (#156) moved several dependencies between devDependencies and dependencies for better categorization and removed redundant entries. * update imports to adjust nodeTestRunner path and remove unused export (#163) updated imports in test files to reflect the correct path for nodeTestRunner. removed redundant export of nodeTestRunner from index file to clean up module structure. In some environments this could cause issues requiring to exclude `node:test`, just removing it for now. * fix sync events not awaited (#164) * refactor(dropzone): extract DropzoneInner and unify state management with zustand (#165) Simplified Dropzone implementation by extracting inner logic to a new component, `DropzoneInner`. Replaced local dropzone state logic with centralized state management using zustand. Adjusted API exports and props accordingly for consistency and maintainability. * replace LiquidJs rendering with simplified renderer (#167) * replace LiquidJs rendering with simplified renderer Removed dependency on LiquidJS and replaced it with a custom templating solution using lodash `get`. Updated corresponding components, editors, and tests to align with the new rendering approach. Removed unused filters and tags. * remove liquid js from package json * feat/cli-generate-types (#166) * init types generation * update type generation for entities and fields Refactored `EntityTypescript` to support improved field types and relations. Added `toType` method overrides for various fields to define accurate TypeScript types. Enhanced CLI `types` command with new options for output style and file handling. Removed redundant test files. * update type generation code and CLI option description removed unused imports definition, adjusted formatting in EntityTypescript, and clarified the CLI style option description. * fix json schema field type generation * reworked system entities to prevent recursive types * reworked system entities to prevent recursive types * remove unused object function * types: use number instead of Generated * update data hooks and api types * update data hooks and api types * update data hooks and api types * update data hooks and api types --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
278 lines
10 KiB
TypeScript
278 lines
10 KiB
TypeScript
import { afterAll, describe, expect, test } from "bun:test";
|
|
import type { Kysely, Transaction } from "kysely";
|
|
import { Perf } from "core/utils";
|
|
import {
|
|
Entity,
|
|
EntityManager,
|
|
LibsqlConnection,
|
|
ManyToOneRelation,
|
|
RepositoryEvents,
|
|
TextField,
|
|
entity as $entity,
|
|
text as $text,
|
|
em as $em,
|
|
} from "data";
|
|
import { getDummyConnection } from "../helper";
|
|
|
|
type E = Kysely<any> | Transaction<any>;
|
|
|
|
const { dummyConnection, afterAllCleanup } = getDummyConnection();
|
|
afterAll(afterAllCleanup);
|
|
|
|
async function sleep(ms: number) {
|
|
return new Promise((resolve) => {
|
|
setTimeout(resolve, ms);
|
|
});
|
|
}
|
|
|
|
describe("[Repository]", async () => {
|
|
test.skip("bulk", async () => {
|
|
//const connection = dummyConnection;
|
|
//const connection = getLocalLibsqlConnection();
|
|
const credentials = null as any; // @todo: determine what to do here
|
|
const connection = new LibsqlConnection(credentials);
|
|
|
|
const em = new EntityManager([], connection);
|
|
/*const emLibsql = new EntityManager([], {
|
|
url: connection.url.replace("https", "libsql"),
|
|
authToken: connection.authToken,
|
|
});*/
|
|
const table = "posts";
|
|
|
|
const client = connection.getClient();
|
|
if (!client) {
|
|
console.log("Cannot perform test without libsql connection");
|
|
return;
|
|
}
|
|
|
|
const conn = em.connection.kysely;
|
|
const selectQ = (e: E) => e.selectFrom(table).selectAll().limit(2);
|
|
const countQ = (e: E) => e.selectFrom(table).select(e.fn.count("*").as("count"));
|
|
|
|
async function executeTransaction(em: EntityManager<any>) {
|
|
return await em.connection.kysely.transaction().execute(async (e) => {
|
|
const res = await selectQ(e).execute();
|
|
const count = await countQ(e).execute();
|
|
|
|
return [res, count];
|
|
});
|
|
}
|
|
|
|
async function executeBatch(em: EntityManager<any>) {
|
|
const queries = [selectQ(conn), countQ(conn)];
|
|
return await em.connection.batchQuery(queries);
|
|
}
|
|
|
|
async function executeSingleKysely(em: EntityManager<any>) {
|
|
const res = await selectQ(conn).execute();
|
|
const count = await countQ(conn).execute();
|
|
return [res, count];
|
|
}
|
|
|
|
async function executeSingleClient(em: EntityManager<any>) {
|
|
const q1 = selectQ(conn).compile();
|
|
const res = await client.execute({
|
|
sql: q1.sql,
|
|
args: q1.parameters as any,
|
|
});
|
|
|
|
const q2 = countQ(conn).compile();
|
|
const count = await client.execute({
|
|
sql: q2.sql,
|
|
args: q2.parameters as any,
|
|
});
|
|
return [res, count];
|
|
}
|
|
|
|
const transaction = await executeTransaction(em);
|
|
const batch = await executeBatch(em);
|
|
|
|
expect(batch).toEqual(transaction as any);
|
|
|
|
const testperf = false;
|
|
if (testperf) {
|
|
const times = 5;
|
|
|
|
const exec = async (
|
|
name: string,
|
|
fn: (em: EntityManager<any>) => Promise<any>,
|
|
em: EntityManager<any>,
|
|
) => {
|
|
const res = await Perf.execute(() => fn(em), times);
|
|
await sleep(1000);
|
|
const info = {
|
|
name,
|
|
total: res.total.toFixed(2),
|
|
avg: (res.total / times).toFixed(2),
|
|
first: res.marks[0].time.toFixed(2),
|
|
last: res.marks[res.marks.length - 1].time.toFixed(2),
|
|
};
|
|
console.log(info.name, info, res.marks);
|
|
return info;
|
|
};
|
|
|
|
const data: any[] = [];
|
|
data.push(await exec("transaction.http", executeTransaction, em));
|
|
data.push(await exec("bulk.http", executeBatch, em));
|
|
data.push(await exec("singleKy.http", executeSingleKysely, em));
|
|
data.push(await exec("singleCl.http", executeSingleClient, em));
|
|
|
|
/*data.push(await exec("transaction.libsql", executeTransaction, emLibsql));
|
|
data.push(await exec("bulk.libsql", executeBatch, emLibsql));
|
|
data.push(await exec("singleKy.libsql", executeSingleKysely, emLibsql));
|
|
data.push(await exec("singleCl.libsql", executeSingleClient, emLibsql));*/
|
|
|
|
console.table(data);
|
|
/**
|
|
* ┌───┬────────────────────┬────────┬────────┬────────┬────────┐
|
|
* │ │ name │ total │ avg │ first │ last │
|
|
* ├───┼────────────────────┼────────┼────────┼────────┼────────┤
|
|
* │ 0 │ transaction.http │ 681.29 │ 136.26 │ 136.46 │ 396.09 │
|
|
* │ 1 │ bulk.http │ 164.82 │ 32.96 │ 32.95 │ 99.91 │
|
|
* │ 2 │ singleKy.http │ 330.01 │ 66.00 │ 65.86 │ 195.41 │
|
|
* │ 3 │ singleCl.http │ 326.17 │ 65.23 │ 61.32 │ 198.08 │
|
|
* │ 4 │ transaction.libsql │ 856.79 │ 171.36 │ 132.31 │ 595.24 │
|
|
* │ 5 │ bulk.libsql │ 180.63 │ 36.13 │ 35.39 │ 107.71 │
|
|
* │ 6 │ singleKy.libsql │ 347.11 │ 69.42 │ 65.00 │ 207.14 │
|
|
* │ 7 │ singleCl.libsql │ 328.60 │ 65.72 │ 62.19 │ 195.04 │
|
|
* └───┴────────────────────┴────────┴────────┴────────┴────────┘
|
|
*/
|
|
}
|
|
});
|
|
|
|
test("count & exists", async () => {
|
|
const items = new Entity("items", [new TextField("label")]);
|
|
const em = new EntityManager([items], dummyConnection);
|
|
|
|
await em.connection.kysely.schema
|
|
.createTable("items")
|
|
.ifNotExists()
|
|
.addColumn("id", "integer", (col) => col.primaryKey().autoIncrement().notNull())
|
|
.addColumn("label", "text")
|
|
.execute();
|
|
|
|
// fill
|
|
await em.connection.kysely
|
|
.insertInto("items")
|
|
.values([{ label: "a" }, { label: "b" }, { label: "c" }])
|
|
.execute();
|
|
|
|
// count all
|
|
const res = await em.repository(items).count();
|
|
expect(res.sql).toBe('select count(*) as "count" from "items"');
|
|
expect(res.count).toBe(3);
|
|
|
|
// count filtered
|
|
const res2 = await em.repository(items).count({ label: { $in: ["a", "b"] } });
|
|
|
|
expect(res2.sql).toBe('select count(*) as "count" from "items" where "label" in (?, ?)');
|
|
expect(res2.parameters).toEqual(["a", "b"]);
|
|
expect(res2.count).toBe(2);
|
|
|
|
// check exists
|
|
const res3 = await em.repository(items).exists({ label: "a" });
|
|
expect(res3.exists).toBe(true);
|
|
|
|
const res4 = await em.repository(items).exists({ label: "d" });
|
|
expect(res4.exists).toBe(false);
|
|
|
|
// for now, allow empty filter
|
|
const res5 = await em.repository(items).exists({});
|
|
expect(res5.exists).toBe(true);
|
|
});
|
|
|
|
test("option: silent", async () => {
|
|
const em = $em({
|
|
items: $entity("items", {
|
|
label: $text(),
|
|
}),
|
|
}).proto.withConnection(getDummyConnection().dummyConnection);
|
|
|
|
// should throw because table doesn't exist
|
|
expect(em.repo("items").findMany({})).rejects.toThrow(/no such table/);
|
|
// should silently return empty result
|
|
expect(
|
|
em
|
|
.repo("items", { silent: true })
|
|
.findMany({})
|
|
.then((r) => r.data),
|
|
).resolves.toEqual([]);
|
|
});
|
|
|
|
test("option: includeCounts", async () => {
|
|
const em = $em({
|
|
items: $entity("items", {
|
|
label: $text(),
|
|
}),
|
|
}).proto.withConnection(getDummyConnection().dummyConnection);
|
|
await em.schema().sync({ force: true });
|
|
|
|
expect(
|
|
em
|
|
.repo("items")
|
|
.findMany({})
|
|
.then((r) => [r.meta.count, r.meta.total]),
|
|
).resolves.toEqual([0, 0]);
|
|
|
|
expect(
|
|
em
|
|
.repo("items", { includeCounts: false })
|
|
.findMany({})
|
|
.then((r) => [r.meta.count, r.meta.total]),
|
|
).resolves.toEqual([undefined, undefined]);
|
|
});
|
|
});
|
|
|
|
describe("[data] Repository (Events)", async () => {
|
|
const items = new Entity("items", [new TextField("label")]);
|
|
const categories = new Entity("categories", [new TextField("label")]);
|
|
const em = new EntityManager([items, categories], dummyConnection, [
|
|
new ManyToOneRelation(categories, items),
|
|
]);
|
|
await em.schema().sync({ force: true });
|
|
const events = new Map<string, any>();
|
|
|
|
em.repository(items).emgr.onAny((event) => {
|
|
// @ts-ignore
|
|
events.set(event.constructor.slug, event);
|
|
});
|
|
em.repository(categories).emgr.onAny((event) => {
|
|
// @ts-ignore
|
|
events.set(event.constructor.slug, event);
|
|
});
|
|
|
|
test("events were fired", async () => {
|
|
const repo = em.repository(items);
|
|
await repo.findId(1);
|
|
await repo.emgr.executeAsyncs();
|
|
expect(events.has(RepositoryEvents.RepositoryFindOneBefore.slug)).toBeTrue();
|
|
expect(events.has(RepositoryEvents.RepositoryFindOneAfter.slug)).toBeTrue();
|
|
events.clear();
|
|
|
|
await repo.findOne({ id: 1 });
|
|
await repo.emgr.executeAsyncs();
|
|
expect(events.has(RepositoryEvents.RepositoryFindOneBefore.slug)).toBeTrue();
|
|
expect(events.has(RepositoryEvents.RepositoryFindOneAfter.slug)).toBeTrue();
|
|
events.clear();
|
|
|
|
await repo.findMany({ where: { id: 1 } });
|
|
await repo.emgr.executeAsyncs();
|
|
expect(events.has(RepositoryEvents.RepositoryFindManyBefore.slug)).toBeTrue();
|
|
expect(events.has(RepositoryEvents.RepositoryFindManyAfter.slug)).toBeTrue();
|
|
events.clear();
|
|
|
|
await repo.findManyByReference(1, "categories");
|
|
await repo.emgr.executeAsyncs();
|
|
expect(events.has(RepositoryEvents.RepositoryFindManyBefore.slug)).toBeTrue();
|
|
expect(events.has(RepositoryEvents.RepositoryFindManyAfter.slug)).toBeTrue();
|
|
events.clear();
|
|
|
|
// check find one on findMany with limit 1
|
|
await repo.findMany({ where: { id: 1 }, limit: 1 });
|
|
await repo.emgr.executeAsyncs();
|
|
expect(events.has(RepositoryEvents.RepositoryFindOneBefore.slug)).toBeTrue();
|
|
expect(events.has(RepositoryEvents.RepositoryFindOneAfter.slug)).toBeTrue();
|
|
events.clear();
|
|
});
|
|
});
|