Skip to content

Commit

Permalink
improve type intellisense readability for client and framework packages
Browse files Browse the repository at this point in the history
  • Loading branch information
wernst committed Jun 7, 2024
1 parent 9f8140f commit 2c2a4d3
Show file tree
Hide file tree
Showing 10 changed files with 83 additions and 59 deletions.
8 changes: 8 additions & 0 deletions .changeset/silly-coins-cry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@triplit/client': patch
'@triplit/svelte': patch
'@triplit/react': patch
'@triplit/db': patch
---

Improve type intellisense readability
1 change: 1 addition & 0 deletions packages/client/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export type {
ModelFromModels,
FetchByIdQueryParams,
QueryBuilder,
Unalias,
} from '@triplit/db';
export { Schema } from '@triplit/db';
export * from './triplit-client.js';
Expand Down
47 changes: 23 additions & 24 deletions packages/client/src/triplit-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,21 @@ import {
DB,
Migration,
UpdateTypeFromModel,
Models,
CollectionNameFromModels,
DBTransaction,
ModelFromModels,
DurableClock,
TriplitError,
InsertTypeFromModel,
Storage,
FetchByIdQueryParams,
FetchResult,
compareCursors,
ValueCursor,
DBFetchOptions as AllDBFetchOptions,
Attribute,
TupleValue,
schemaToJSON,
Unalias,
} from '@triplit/db';
import { getUserId } from './token.js';
import { UnrecognizedFetchPolicyError } from './errors.js';
Expand All @@ -31,8 +30,6 @@ import {
ClientQuery,
ClientSchema,
clientQueryBuilder,
prepareFetchByIdQuery,
prepareFetchOneQuery,
} from './utils/query.js';
import { RemoteClient } from './remote-client.js';
import { Logger } from '@triplit/types/logger.js';
Expand Down Expand Up @@ -283,7 +280,7 @@ export class TriplitClient<M extends ClientSchema | undefined = undefined> {
async fetch<CQ extends ClientQuery<M, any>>(
query: CQ,
options?: Partial<FetchOptions>
): Promise<ClientFetchResult<CQ>> {
): Promise<Unalias<ClientFetchResult<CQ>>> {
// ID is currently used to trace the lifecycle of a query/subscription across logs
// @ts-ignore
query = addLoggingIdToQuery(query);
Expand Down Expand Up @@ -332,7 +329,7 @@ export class TriplitClient<M extends ClientSchema | undefined = undefined> {
private async fetchLocal<CQ extends ClientQuery<M, any>>(
query: CQ,
options?: Partial<DBFetchOptions>
): Promise<ClientFetchResult<CQ>> {
): Promise<Unalias<ClientFetchResult<CQ>>> {
const scope = parseScope(query);
this.logger.debug('fetchLocal START', query, scope);
const res = await this.db.fetch(query, {
Expand All @@ -341,14 +338,14 @@ export class TriplitClient<M extends ClientSchema | undefined = undefined> {
...(options ?? {}),
});
this.logger.debug('fetchLocal END', res);
return res as ClientFetchResult<CQ>;
return res;
}

async fetchById<CN extends CollectionNameFromModels<M>>(
collectionName: CN,
id: string,
options?: Partial<FetchOptions>
): Promise<ClientFetchResultEntity<ClientQuery<M, CN>> | null> {
) {
this.logger.debug('fetchById START', collectionName, id, options);
const query = this.query(collectionName).id(id).build();
const result = await this.fetchOne(query, options);
Expand All @@ -359,7 +356,7 @@ export class TriplitClient<M extends ClientSchema | undefined = undefined> {
async fetchOne<CQ extends ClientQuery<M, any>>(
query: CQ,
options?: Partial<FetchOptions>
): Promise<ClientFetchResultEntity<CQ> | null> {
) {
// ID is currently used to trace the lifecycle of a query/subscription across logs
// @ts-ignore
query = addLoggingIdToQuery(query);
Expand All @@ -372,7 +369,7 @@ export class TriplitClient<M extends ClientSchema | undefined = undefined> {

async insert<CN extends CollectionNameFromModels<M>>(
collectionName: CN,
object: InsertTypeFromModel<ModelFromModels<M, CN>>
object: Unalias<InsertTypeFromModel<ModelFromModels<M, CN>>>
) {
this.logger.debug('insert START', collectionName, object);
const resp = await this.db.insert(collectionName, object, {
Expand All @@ -390,7 +387,7 @@ export class TriplitClient<M extends ClientSchema | undefined = undefined> {
collectionName: CN,
entityId: string,
updater: (
entity: UpdateTypeFromModel<ModelFromModels<M, CN>>
entity: Unalias<UpdateTypeFromModel<ModelFromModels<M, CN>>>
) => void | Promise<void>
) {
this.logger.debug('update START', collectionName, entityId);
Expand Down Expand Up @@ -449,7 +446,7 @@ export class TriplitClient<M extends ClientSchema | undefined = undefined> {
subscribe<CQ extends ClientQuery<M, any, any, any>>(
query: CQ,
onResults: (
results: ClientFetchResult<CQ>,
results: Unalias<ClientFetchResult<CQ>>,
info: { hasRemoteFulfilled: boolean }
) => void | Promise<void>,
onError?: (error: any) => void | Promise<void>,
Expand All @@ -467,7 +464,7 @@ export class TriplitClient<M extends ClientSchema | undefined = undefined> {
return this.db.subscribe(
query,
(results) =>
onResults(results as ClientFetchResult<CQ>, {
onResults(results, {
hasRemoteFulfilled: false,
}),
onError,
Expand All @@ -488,13 +485,13 @@ export class TriplitClient<M extends ClientSchema | undefined = undefined> {
let unsubscribeRemote = () => {};
let hasRemoteFulfilled = false;
let fulfilledTimeout: ReturnType<typeof setTimeout> | null = null;
let results: FetchResult<CQ>;
let results: Unalias<FetchResult<CQ>>;
const userResultsCallback = onResults;
const userErrorCallback = onError;
onResults = (results, info) => {
// Ensure we dont re-fire the callback if we've already unsubscribed
if (unsubscribed) return;
userResultsCallback(results as ClientFetchResult<CQ>, info);
userResultsCallback(results, info);
};
onError = userErrorCallback
? (error) => {
Expand All @@ -503,10 +500,12 @@ export class TriplitClient<M extends ClientSchema | undefined = undefined> {
userErrorCallback(error);
}
: undefined;
const clientSubscriptionCallback = (newResults: FetchResult<CQ>) => {
const clientSubscriptionCallback = (
newResults: Unalias<FetchResult<CQ>>
) => {
results = newResults;
this.logger.debug('subscribe RESULTS', results);
onResults(results as ClientFetchResult<CQ>, { hasRemoteFulfilled });
onResults(results, { hasRemoteFulfilled });
};
unsubscribeLocal = this.db.subscribe(
query,
Expand All @@ -527,7 +526,7 @@ export class TriplitClient<M extends ClientSchema | undefined = undefined> {
// This is a hack to make sure we don't call onRemoteFulfilled before
// the local subscription callback has had a chance to refire
fulfilledTimeout = setTimeout(() => {
clientSubscriptionCallback(results as ClientFetchResult<CQ>);
clientSubscriptionCallback(results);
opts.onRemoteFulfilled?.();
}, 250);
};
Expand All @@ -551,7 +550,7 @@ export class TriplitClient<M extends ClientSchema | undefined = undefined> {
subscribeWithPagination<CQ extends ClientQuery<M, any>>(
query: CQ,
onResults: (
results: ClientFetchResult<CQ>,
results: Unalias<ClientFetchResult<CQ>>,
info: {
hasRemoteFulfilled: boolean;
hasNextPage: boolean;
Expand Down Expand Up @@ -594,7 +593,7 @@ export class TriplitClient<M extends ClientSchema | undefined = undefined> {
// If we have an after, the limit will increase by 1
query.limit = requestedLimit! + 1 + (query.after ? 1 : 0);
subscriptionResultHandler = (
results: ClientFetchResult<CQ>,
results: Unalias<ClientFetchResult<CQ>>,
info: { hasRemoteFulfilled: boolean }
) => {
const cursorAttr = query.order?.[0]?.[0];
Expand Down Expand Up @@ -667,7 +666,7 @@ export class TriplitClient<M extends ClientSchema | undefined = undefined> {
options
);
} else {
onResults(new Map(entries) as ClientFetchResult<CQ>, {
onResults(new Map(entries), {
...info,
hasNextPage: hasNextPage,
hasPreviousPage: hasPreviousPage,
Expand Down Expand Up @@ -734,7 +733,7 @@ export class TriplitClient<M extends ClientSchema | undefined = undefined> {
subscribeWithExpand<CQ extends ClientQuery<M, any>>(
query: CQ,
onResults: (
results: ClientFetchResult<CQ>,
results: Unalias<ClientFetchResult<CQ>>,
info: {
hasRemoteFulfilled: boolean;
hasMore: boolean;
Expand All @@ -759,13 +758,13 @@ export class TriplitClient<M extends ClientSchema | undefined = undefined> {
const originalPageSize = query.limit;
query.limit = query.limit + 1;
subscriptionResultHandler = (
results: ClientFetchResult<CQ>,
results: Unalias<ClientFetchResult<CQ>>,
info: { hasRemoteFulfilled: boolean }
) => {
const hasMore = results.size >= query.limit!;
let entries = Array.from(results.entries());
if (hasMore) entries = entries.slice(0, -1);
onResults(new Map(entries) as ClientFetchResult<CQ>, {
onResults(new Map(entries), {
hasRemoteFulfilled: info.hasRemoteFulfilled,
hasMore,
});
Expand Down
2 changes: 1 addition & 1 deletion packages/client/src/utils/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export type ClientFetchResult<C extends ClientQuery<any, any>> = Map<

export type ClientSchema = Models<any, any>;

export type ClientFetchResultEntity<C extends ClientQuery<any, any>> =
export type ClientFetchResultEntity<C extends ClientQuery<any, any, any, any>> =
ReturnTypeFromQuery<C>;

export type SyncStatus = 'pending' | 'confirmed' | 'all';
Expand Down
38 changes: 23 additions & 15 deletions packages/client/src/worker-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,16 @@ import type {
InfiniteSubscription,
PaginatedSubscription,
SubscriptionOptions,
TriplitClient,
} from './triplit-client.js';
import {
ChangeTracker,
CollectionNameFromModels,
CollectionQuery,
DBTransaction,
FetchByIdQueryParams,
InsertTypeFromModel,
JSONToSchema,
ModelFromModels,
Unalias,
UpdateTypeFromModel,
createUpdateProxy,
schemaToJSON,
Expand All @@ -25,7 +24,7 @@ import {
ClientFetchResult,
ClientFetchResultEntity,
ClientQuery,
ClientQueryBuilder,
ClientQueryDefault,
ClientSchema,
clientQueryBuilder,
} from './utils/query.js';
Expand Down Expand Up @@ -74,7 +73,7 @@ export class WorkerClient<M extends ClientSchema | undefined = undefined> {
async fetch<CQ extends ClientQuery<M, any>>(
query: CQ,
options?: Partial<FetchOptions>
): Promise<ClientFetchResult<CQ>> {
): Promise<Unalias<ClientFetchResult<CQ>>> {
await this.initialized;
// @ts-expect-error
return this.clientWorker.fetch(query, options);
Expand All @@ -88,26 +87,33 @@ export class WorkerClient<M extends ClientSchema | undefined = undefined> {
collectionName: CN,
id: string,
options?: Partial<FetchOptions>
) {
): Promise<Unalias<
ClientFetchResultEntity<ClientQueryDefault<M, CN>>
> | null> {
await this.initialized;
return this.clientWorker.fetchById(
// @ts-ignore
// @ts-expect-error
collectionName,
id,
options
);
}
async fetchOne<CQ extends ClientQuery<M, any>>(
async fetchOne<CQ extends ClientQuery<M, any, any, any>>(
query: CQ,
options?: Partial<FetchOptions>
): Promise<ClientFetchResultEntity<CQ> | null> {
): Promise<Unalias<ClientFetchResultEntity<CQ>> | null> {
await this.initialized;
return this.clientWorker.fetchOne(query, options);
}
async insert<CN extends CollectionNameFromModels<M>>(
collectionName: CN,
entity: InsertTypeFromModel<ModelFromModels<M, CN>>
) {
entity: Unalias<InsertTypeFromModel<ModelFromModels<M, CN>>>
): Promise<{
txId: string | undefined;
output:
| Unalias<ClientFetchResultEntity<ClientQueryDefault<M, CN>>>
| undefined;
}> {
await this.initialized;
return this.clientWorker.insert(
// @ts-ignore
Expand All @@ -119,7 +125,7 @@ export class WorkerClient<M extends ClientSchema | undefined = undefined> {
collectionName: CN,
entityId: string,
updater: (
entity: UpdateTypeFromModel<ModelFromModels<M, CN>>
entity: Unalias<UpdateTypeFromModel<ModelFromModels<M, CN>>>
) => void | Promise<void>
) {
await this.initialized;
Expand All @@ -133,7 +139,9 @@ export class WorkerClient<M extends ClientSchema | undefined = undefined> {
collectionName === '_metadata'
? createUpdateProxy<M, any>(changes, entity)
: createUpdateProxy<M, any>(changes, entity, schema, collectionName);
await updater(updateProxy);
await updater(
updateProxy as Unalias<UpdateTypeFromModel<ModelFromModels<M, CN>>>
);
return changes.getTuples();
});
}
Expand Down Expand Up @@ -166,7 +174,7 @@ export class WorkerClient<M extends ClientSchema | undefined = undefined> {
subscribe<CQ extends ClientQuery<M, any, any, any>>(
query: CQ,
onResults: (
results: ClientFetchResult<CQ>,
results: Unalias<ClientFetchResult<CQ>>,
info: { hasRemoteFulfilled: boolean }
) => void | Promise<void>,
onError?: (error: any) => void | Promise<void>,
Expand Down Expand Up @@ -201,7 +209,7 @@ export class WorkerClient<M extends ClientSchema | undefined = undefined> {
subscribeWithPagination<CQ extends ClientQuery<M, any>>(
query: CQ,
onResults: (
results: ClientFetchResult<CQ>,
results: Unalias<ClientFetchResult<CQ>>,
info: {
hasRemoteFulfilled: boolean;
hasNextPage: boolean;
Expand Down Expand Up @@ -238,7 +246,7 @@ export class WorkerClient<M extends ClientSchema | undefined = undefined> {
subscribeWithExpand<CQ extends ClientQuery<M, any>>(
query: CQ,
onResults: (
results: ClientFetchResult<CQ>,
results: Unalias<ClientFetchResult<CQ>>,
info: {
hasRemoteFulfilled: boolean;
hasMore: boolean;
Expand Down
2 changes: 1 addition & 1 deletion packages/db/src/db-transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -719,7 +719,7 @@ export class DBTransaction<M extends Models<any, any> | undefined> {
async fetchOne<Q extends CollectionQuery<M, any>>(
query: Q,
options: DBFetchOptions = {}
): Promise<Unalias<FetchResultEntity<Q> | null>> {
): Promise<Unalias<FetchResultEntity<Q>> | null> {
query = { ...query, limit: 1 };
const result = await this.fetch(query, options);
const entity = [...result.values()][0];
Expand Down
14 changes: 10 additions & 4 deletions packages/react/src/use-entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@ import {
Models,
CollectionNameFromModels,
SubscriptionOptions,
ReturnTypeFromQuery,
FetchByIdQueryParams,
Unalias,
ClientFetchResultEntity,
ClientQueryDefault,
} from '@triplit/client';
import { useQuery } from './use-query.js';
import type { WorkerClient } from '@triplit/client/worker-client';
import { useQueryOne } from './use-query-one.js';

Expand All @@ -19,7 +18,14 @@ export function useEntity<
collectionName: CN,
id: string,
options?: Partial<SubscriptionOptions>
) {
): {
fetching: boolean;
fetchingLocal: boolean;
fetchingRemote: boolean;
result: Unalias<ClientFetchResultEntity<ClientQueryDefault<M, CN>>> | null;
results: Unalias<ClientFetchResultEntity<ClientQueryDefault<M, CN>>> | null;
error: any;
} {
let builder = client.query(collectionName).id(id);
const queryData = useQueryOne(client, builder, options);
return {
Expand Down
Loading

0 comments on commit 2c2a4d3

Please sign in to comment.