Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce immutable query fragments #409

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 27 additions & 16 deletions src/queryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,37 @@ export abstract class QueryBuilder {
__query: string = ""

public constructor() {
this.__attr("__typename")
this.__attr("__typename", true)
if (typeof (this as any).id === "function") (this as any).id()
}

protected __attr(attr: string): this {
return this._(attr)
protected __attr(attr: string, mutable?: boolean): this {
return this._(attr, mutable)
}

public __clone() {
return Object.assign(Object.create(Object.getPrototypeOf(this)), this)
}

// raw is exposed, to be able to add free form gql in the middle
public _(str: string): this {
this.__query += `${str}\n` // TODO: restore depth / formatting by passing base depth to constructor: ${"".padStart(this.__qb.stack.length * 2)}
return this
public _(str: string, mutable?: boolean): this {
if (mutable || str === "id") {
this.__query += `${str}\n`
return this
} else {
const clone = this.__clone()
clone.__query += `${str}\n`

return clone
}
}

protected __child<T extends QueryBuilder>(
childName: string,
childType: new () => T,
builder?: string | ((q: T) => T) | T
): this {
this._(`${childName} {\n`)
this.__buildChild(childType, builder)
this._(`}`)
return this
return this._(`${childName} {\n`).__buildChild(childType, builder)._(`}`)
}

// used for interfaces and unions
Expand All @@ -45,13 +53,16 @@ export abstract class QueryBuilder {
) {
// already instantiated child builder
if (builder instanceof QueryBuilder) {
this._(builder.toString())
return this._(builder.toString())
} else {
const childBuilder = new childType()
if (typeof builder === "string") childBuilder._(builder)
else if (typeof builder === "function") builder(childBuilder)
// undefined is ok as well, no fields at all
this._(childBuilder.toString())
const baseChildBuilder = new childType()
const childBuilder =
typeof builder === "string"
? baseChildBuilder._(builder)
: typeof builder === "function"
? builder(baseChildBuilder)
: baseChildBuilder
return this._(childBuilder.toString())
}
}

Expand Down