Skip to content

Commit

Permalink
Add explicit toJSON() method to queries
Browse files Browse the repository at this point in the history
allows for e.g.:

const articles = await Article.with("user").orderBy("createdAt", "desc").toJSON();

from a loader to explicitly return the serialized version of a model to provide it to a component. this makes it so that the version of the model that is provided during SSR is exactly equivalent to the version of the model that is made available to the component when rendered on the client. otherwise, the data made available to the component during SSR when using single fetch is the actual model instance.
  • Loading branch information
acusti committed Jan 21, 2025
1 parent c834819 commit 80ed4bf
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions packages/superflare/src/query-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export class QueryBuilder {
private $eagerLoad: string[] = [];
private $limit: number | null = null;
private $single: boolean = false;
private $serialize: boolean = false;
private $modelClass: any;
private $afterHooks: ((results: any) => void)[] = [];

Expand Down Expand Up @@ -69,6 +70,9 @@ export class QueryBuilder {

results = await this.eagerLoadRelations(results);

results = this.$serialize
? results.map((result: typeof this.$modelClass) => result.toJSON())
: results;
let result = this.$single ? results[0] ?? null : results;

this.runCallbacks(result);
Expand Down Expand Up @@ -139,6 +143,11 @@ export class QueryBuilder {
return this.limit(1);
}

toJSON(): this {
this.$serialize = true;
return this;
}

async insert(attributes: Record<string, any>): Promise<any> {
try {
const results = await this.connection()
Expand Down

0 comments on commit 80ed4bf

Please sign in to comment.