Skip to content

Commit

Permalink
feat: general refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
bbtgnn committed Feb 29, 2024
1 parent 79e5ca5 commit 12d80fd
Show file tree
Hide file tree
Showing 8 changed files with 78 additions and 110 deletions.
3 changes: 1 addition & 2 deletions src/_modules/components/Collection.svelte
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
<script lang="ts">
import type { SortProp } from '$modules/dao/db';
import type { SortProp } from '$modules/dao/sorting';
import { db } from '$modules/index';
import type { CollectionName } from '$modules/database';
// import type { SortProp } from '$modules/db';
//
Expand Down
6 changes: 3 additions & 3 deletions src/_modules/components/Relation.svelte
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
<script lang="ts">
import { db } from '$modules';
import { type BaseRelationTransform } from '$modules/fields';
import type { RelationField } from '$modules/fields';
import type { CollectionName } from '$modules/database';
type C = $$Generic<CollectionName>;
export let relation: BaseRelationTransform<C> | undefined;
export let relation: RelationField<C> | undefined;
</script>

{#if relation}
<slot relation={db.get_document(relation?.collection, relation.id)} />
<slot relation={db.get_document(relation?.collection, relation.document)} />
{/if}
4 changes: 2 additions & 2 deletions src/_modules/dao/base_document_handling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {

import { Type as T, type Static, type TAnySchema, type StaticDecode } from '@sinclair/typebox';
import { Value } from '@sinclair/typebox/value';

import document_module_record from '$database/_export';

import { href } from '../utils';
Expand Down Expand Up @@ -94,8 +95,7 @@ export function parse_base_document<T extends TAnySchema>(
},
catch: () => {
const errors = [...Value.Errors(schema, base_document.props)];
console.log(base_document, errors);
return new Error(`Parse error: ${base_document.path}`);
return new Error(`Parse error: ${base_document.path} \n ${JSON.stringify(errors, null, 2)}`);
}
});
}
54 changes: 6 additions & 48 deletions src/_modules/dao/db.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { pipe, Effect, ReadonlyArray as A, Option as O } from 'effect';
// Effect must be the imported before other imports that use effect!

import { Type as T, type Static } from '@sinclair/typebox';
// Effect must be imported before other imports that use effect!

import type {
Collection,
Expand All @@ -20,8 +18,8 @@ import {
} from './base_document_handling';

import { Value } from '@sinclair/typebox/value';
import _ from 'lodash';
import { base } from '$app/paths';
import { sort_documents, type GetCollectionOptions } from './sorting';

//

Expand Down Expand Up @@ -86,51 +84,11 @@ export function get_collection<C extends CollectionName>(
get_collection_schema(collection_name)
]),
Effect.flatMap(([documents, schema]) =>
Effect.all(documents.map((doc) => parse_base_document(doc, schema)))
pipe(
Effect.all(documents.map((doc) => parse_base_document(doc, schema))),
Effect.map((documents) => sort_documents(documents, options.sort))
)
),
Effect.map((documents) => {
if (options.sort) {
const sort = parse_sort_prop(options.sort);
return _.orderBy(
documents,
sort.keys.map((k) => `props.${k}`),
sort.orders
);
} else {
return documents;
}
}),
Effect.runSync
);
}

export const sort_order_schema = T.Union([T.Literal('asc'), T.Literal('desc')]);
export type SortOrder = Static<typeof sort_order_schema>;

export const base_sort_prop_schema = T.Tuple([T.String(), sort_order_schema]);
export type BaseSortProp<C extends CollectionName> = [keyof Collection<C>, SortOrder];
export type SortProp<C extends CollectionName> = BaseSortProp<C> | BaseSortProp<C>[];

export type ParsedSortProp = { keys: string[]; orders: SortOrder[] };

type GetCollectionOptions<C extends CollectionName> = {
sort?: SortProp<C>;
};

function parse_sort_prop<C extends CollectionName>(sortProp: SortProp<C>): ParsedSortProp {
if (Value.Check(base_sort_prop_schema, sortProp))
return {
keys: [sortProp[0]],
orders: [sortProp[1]]
};
else if (Value.Check(T.Array(base_sort_prop_schema), sortProp)) {
return {
keys: sortProp.map((base) => base[0]),
orders: sortProp.map((base) => base[1])
};
} else
return {
keys: [],
orders: []
};
}
52 changes: 52 additions & 0 deletions src/_modules/dao/sorting.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import type { Collection, CollectionName, Document } from '$modules/types';
import { Type as T, type Static } from '@sinclair/typebox';
import { Value } from '@sinclair/typebox/value';
import _ from 'lodash';

const sort_order_schema = T.Union([T.Literal('asc'), T.Literal('desc')]);
type SortOrder = Static<typeof sort_order_schema>;

const base_sort_prop_schema = T.Tuple([T.String(), sort_order_schema]);
type BaseSortProp<C extends CollectionName> = [keyof Collection<C>, SortOrder];

export type SortProp<C extends CollectionName> = BaseSortProp<C> | BaseSortProp<C>[];

type ParsedSortProp = { keys: string[]; orders: SortOrder[] };

export type GetCollectionOptions<C extends CollectionName> = {
sort?: SortProp<C>;
};

function parse_sort_prop<C extends CollectionName>(sortProp: SortProp<C>): ParsedSortProp {
if (Value.Check(base_sort_prop_schema, sortProp))
return {
keys: [sortProp[0]],
orders: [sortProp[1]]
};
else if (Value.Check(T.Array(base_sort_prop_schema), sortProp)) {
return {
keys: sortProp.map((base) => base[0]),
orders: sortProp.map((base) => base[1])
};
} else
return {
keys: [],
orders: []
};
}

export function sort_documents<C extends CollectionName>(
documents: Document<C>[],
sort_prop: SortProp<C> | undefined = undefined
): Document<C>[] {
if (sort_prop) {
const sort = parse_sort_prop(sort_prop);
return _.orderBy(
documents,
sort.keys.map((k) => `props.${k}`),
sort.orders
);
} else {
return documents;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@ import type { Plugin } from 'vite';
//

const collections_directory = 'src/routes/(database)';
const output_directory = 'src/_modules/database_index.ts';
const output_file = 'src/_modules/database_index.ts';

export function save_database_index_plugin(): Plugin {
return {
name: 'save_database_index',
buildStart: () => {
save_database_index(collections_directory, output_directory);
save_database_index(collections_directory, output_file);
},
handleHotUpdate: ({ file }) => {
if (file.includes(output_directory)) return;
save_database_index(collections_directory, output_directory);
if (file.includes(output_file)) return;
save_database_index(collections_directory, output_file);
}
};
}
Expand Down
59 changes: 9 additions & 50 deletions src/_modules/fields.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { formatDate } from 'date-fns/format';
import { Type as T } from '@sinclair/typebox';
import { Type as T, type StaticDecode } from '@sinclair/typebox';
import { database_index, database_index_schema } from './database_index';
import type { CollectionName } from './database';
import type { DocumentName, Document } from './types';

import { db } from '$modules';

//

export const String = T.String;
export const Number = T.Number;
export const Object = T.Object;
Expand All @@ -14,9 +15,6 @@ export const Boolean = T.Boolean;
export const Union = T.Union;
export const Literal = T.Literal;

// import tree from './database_index';
// import type { CollectionEntry, CollectionName } from './database';

/* Date */

type DateFormats = 'yyyy-MM' | 'yyyy-MM-dd';
Expand Down Expand Up @@ -48,48 +46,13 @@ function dateToString(dateFormat: string) {

/* File */

// TODO - Add regex for path
export const File = () => T.String({});

/* Relation */

// export function Relation<C extends CollectionName>(collection_name: C) {
// const collection_entries = database_index[collection_name];
// return T.Union(collection_entries.map((name) => BaseRelation(collection_name, name)));
// }

// export function BaseRelation<C extends CollectionName>(
// collection_name: C,
// entry_name: DocumentName<C>
// ) {
// return T.Transform(T.Literal(entry_name))
// .Decode((id) => ({
// collection: collection_name,
// id,
// get: () => db.get_document(collection_name, id)
// }))
// .Encode((entry) => entry.id);
// }

// export type BaseRelationTransform<C extends CollectionName> = {
// collection: C;
// id: DocumentName<C>;
// get: () => Promise<EntryResponse<C>>;
// };
type Relation<C extends CollectionName> = (typeof database_index_schema)['properties'][C];

// type O = CollectionEntries<'work_experiences'>;

// // Map each element of tuple T to TLiteral
// type MapLiteral<T extends readonly string[]> = {
// [P in keyof T]: TLiteral<T[P]>;
// };

// // Remove readonly from type
// type Writable<T> = { -readonly [P in keyof T]: T[P] };

// type RelationLiterals<C extends CollectionName> = Writable<MapLiteral<CollectionEntries<C>>>;
// type O = RelationLiterals<"organizations">

export function BaseRelation<C extends CollectionName>(collection_name: C): Relation<C> {
const collection_entries = database_index[collection_name];
// @ts-expect-error - Avoid type overlap
Expand All @@ -98,16 +61,12 @@ export function BaseRelation<C extends CollectionName>(collection_name: C): Rela

export function Relation<C extends CollectionName>(collection_name: C) {
return T.Transform(BaseRelation(collection_name))
.Decode((id) => ({
.Decode((document) => ({
collection: collection_name,
id,
get: () => db.get_document(collection_name, id)
document,
get: () => db.get_document(collection_name, document)
}))
.Encode((entry) => entry.id);
.Encode((field) => field.document);
}

export type BaseRelationTransform<C extends CollectionName> = {
collection: C;
id: DocumentName<C>;
get: () => Document<C>;
};
export type RelationField<C extends CollectionName> = StaticDecode<ReturnType<typeof Relation<C>>>;
2 changes: 1 addition & 1 deletion vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { save_database_index_plugin } from './src/_modules/code_generation';
import { save_database_index_plugin } from './src/_modules/database_index_generation';
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vitest/config';

Expand Down

0 comments on commit 12d80fd

Please sign in to comment.