@m1212e/rumble 0.10.9 → 0.10.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/index.cjs +6 -6
- package/index.cjs.map +1 -1
- package/index.d.cts +30 -8
- package/index.d.ts +30 -8
- package/index.js +6 -6
- package/index.js.map +1 -1
- package/package.json +1 -1
package/index.d.cts
CHANGED
@@ -2,7 +2,7 @@ import * as SchemaBuilder from '@pothos/core';
|
|
2
2
|
import SchemaBuilder__default, { SchemaTypes, BasePlugin, PothosOutputFieldConfig } from '@pothos/core';
|
3
3
|
import { GraphQLFieldResolver, GraphQLError } from 'graphql';
|
4
4
|
import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
|
5
|
-
import { PgEnum } from 'drizzle-orm/pg-core';
|
5
|
+
import { PgDatabase, PgEnum } from 'drizzle-orm/pg-core';
|
6
6
|
import * as _pothos_plugin_drizzle from '@pothos/plugin-drizzle';
|
7
7
|
import { DrizzleClient } from '@pothos/plugin-drizzle';
|
8
8
|
import * as fets from 'fets';
|
@@ -10,6 +10,9 @@ import * as graphql_yoga from 'graphql-yoga';
|
|
10
10
|
import { createPubSub, YogaServerOptions } from 'graphql-yoga';
|
11
11
|
import * as drizzle_orm from 'drizzle-orm';
|
12
12
|
import { useSofa } from 'sofa-api';
|
13
|
+
import { MySqlDatabase } from 'drizzle-orm/mysql-core';
|
14
|
+
import { SingleStoreDatabase } from 'drizzle-orm/singlestore-core';
|
15
|
+
import { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core';
|
13
16
|
|
14
17
|
declare const pluginName = "ManualFiltersPlugin";
|
15
18
|
|
@@ -179,6 +182,8 @@ type GenericDrizzleDbTypeConstraints = {
|
|
179
182
|
}>) => any;
|
180
183
|
};
|
181
184
|
};
|
185
|
+
execute?: PgDatabase<any, any>["execute"] | MySqlDatabase<any, any>["execute"] | SingleStoreDatabase<any, any>["execute"] | undefined;
|
186
|
+
run?: BaseSQLiteDatabase<any, any>["run"];
|
182
187
|
} & DrizzleClient;
|
183
188
|
|
184
189
|
type CustomRumblePothosConfig = Omit<ConstructorParameters<typeof SchemaBuilder__default>[0], "smartSubscriptions" | "drizzle">;
|
@@ -217,6 +222,23 @@ type RumbleInput<UserContext extends Record<string, any>, DB extends GenericDriz
|
|
217
222
|
* @default 100
|
218
223
|
*/
|
219
224
|
defaultLimit?: number | undefined | null;
|
225
|
+
/**
|
226
|
+
* rumble supports fuzzy search for the query helpers. This enables the users of your API to search for entities via fuzzy search inputs.
|
227
|
+
* This currently only is supported by postgres databases and will fail if enabled on other dialects.
|
228
|
+
*
|
229
|
+
* Please note that this will install the pg_trgm extension on startup if your database does not have it already installed.
|
230
|
+
* https://www.postgresql.org/docs/current/pgtrgm.html
|
231
|
+
*/
|
232
|
+
search?: {
|
233
|
+
/**
|
234
|
+
* Whether search is enabled
|
235
|
+
*/
|
236
|
+
enabled?: boolean;
|
237
|
+
/**
|
238
|
+
* The threshold for cutting off non matching results. Defaults to 0.1. Lower = more results.
|
239
|
+
*/
|
240
|
+
threshold?: number;
|
241
|
+
} | undefined;
|
220
242
|
};
|
221
243
|
|
222
244
|
type NumberWhereInputArgument = {
|
@@ -332,7 +354,7 @@ declare const rumble: <UserContext extends Record<string, any>, DB extends Gener
|
|
332
354
|
readonly limit: any;
|
333
355
|
};
|
334
356
|
};
|
335
|
-
|
357
|
+
runtimeFilters: (action: Action) => (keyof DB["query"] extends infer T_4 extends keyof DB["query"] ? { [key_3 in T_4]: { [key_4 in Action]: Filter<UserContext, any>[]; }; } : never)[key_5][Action];
|
336
358
|
}; } : never;
|
337
359
|
};
|
338
360
|
/**
|
@@ -354,7 +376,7 @@ declare const rumble: <UserContext extends Record<string, any>, DB extends Gener
|
|
354
376
|
readonly limit: any;
|
355
377
|
};
|
356
378
|
};
|
357
|
-
|
379
|
+
runtimeFilters: (action: Action) => (keyof DB["query"] extends infer T_4 extends keyof DB["query"] ? { [key_3 in T_4]: { [key_4 in Action]: Filter<UserContext, any>[]; }; } : never)[key_5][Action];
|
358
380
|
}; } : never;
|
359
381
|
}>;
|
360
382
|
DrizzleRelations: DB["_"]["relations"];
|
@@ -441,7 +463,7 @@ declare const rumble: <UserContext extends Record<string, any>, DB extends Gener
|
|
441
463
|
readonly limit: any;
|
442
464
|
};
|
443
465
|
};
|
444
|
-
|
466
|
+
runtimeFilters: (action: Action) => (keyof DB["query"] extends infer T_5 extends keyof DB["query"] ? { [key_3 in T_5]: { [key_4 in Action]: Filter<UserContext, any>[]; }; } : never)[key_5][Action];
|
445
467
|
}; } : never;
|
446
468
|
}>;
|
447
469
|
DrizzleRelations: DB["_"]["relations"];
|
@@ -514,7 +536,7 @@ declare const rumble: <UserContext extends Record<string, any>, DB extends Gener
|
|
514
536
|
readonly limit: any;
|
515
537
|
};
|
516
538
|
};
|
517
|
-
|
539
|
+
runtimeFilters: (action: Action) => (keyof DB["query"] extends infer T_5 extends keyof DB["query"] ? { [key_3 in T_5]: { [key_4 in Action]: Filter<UserContext, any>[]; }; } : never)[key_5][Action];
|
518
540
|
}; } : never;
|
519
541
|
}>;
|
520
542
|
DrizzleRelations: DB["_"]["relations"];
|
@@ -566,7 +588,7 @@ declare const rumble: <UserContext extends Record<string, any>, DB extends Gener
|
|
566
588
|
readonly limit: any;
|
567
589
|
};
|
568
590
|
};
|
569
|
-
|
591
|
+
runtimeFilters: (action: Action) => (keyof DB["query"] extends infer T_5 extends keyof DB["query"] ? { [key_3 in T_5]: { [key_4 in Action]: Filter<UserContext, any>[]; }; } : never)[key_5][Action];
|
570
592
|
}; } : never;
|
571
593
|
}>;
|
572
594
|
DrizzleRelations: DB["_"]["relations"];
|
@@ -620,7 +642,7 @@ declare const rumble: <UserContext extends Record<string, any>, DB extends Gener
|
|
620
642
|
readonly limit: any;
|
621
643
|
};
|
622
644
|
};
|
623
|
-
|
645
|
+
runtimeFilters: (action: Action) => (keyof DB["query"] extends infer T_5 extends keyof DB["query"] ? { [key_3 in T_5]: { [key_4 in Action]: Filter<UserContext, any>[]; }; } : never)[key_5][Action];
|
624
646
|
}; } : never;
|
625
647
|
}>;
|
626
648
|
DrizzleRelations: DB["_"]["relations"];
|
@@ -702,7 +724,7 @@ declare const rumble: <UserContext extends Record<string, any>, DB extends Gener
|
|
702
724
|
readonly limit: any;
|
703
725
|
};
|
704
726
|
};
|
705
|
-
|
727
|
+
runtimeFilters: (action: Action) => (keyof DB["query"] extends infer T_6 extends keyof DB["query"] ? { [key_3 in T_6]: { [key_4 in Action]: Filter<UserContext, any>[]; }; } : never)[key_5][Action];
|
706
728
|
}; } : never;
|
707
729
|
}>;
|
708
730
|
DrizzleRelations: DB["_"]["relations"];
|
package/index.d.ts
CHANGED
@@ -2,7 +2,7 @@ import * as SchemaBuilder from '@pothos/core';
|
|
2
2
|
import SchemaBuilder__default, { SchemaTypes, BasePlugin, PothosOutputFieldConfig } from '@pothos/core';
|
3
3
|
import { GraphQLFieldResolver, GraphQLError } from 'graphql';
|
4
4
|
import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
|
5
|
-
import { PgEnum } from 'drizzle-orm/pg-core';
|
5
|
+
import { PgDatabase, PgEnum } from 'drizzle-orm/pg-core';
|
6
6
|
import * as _pothos_plugin_drizzle from '@pothos/plugin-drizzle';
|
7
7
|
import { DrizzleClient } from '@pothos/plugin-drizzle';
|
8
8
|
import * as fets from 'fets';
|
@@ -10,6 +10,9 @@ import * as graphql_yoga from 'graphql-yoga';
|
|
10
10
|
import { createPubSub, YogaServerOptions } from 'graphql-yoga';
|
11
11
|
import * as drizzle_orm from 'drizzle-orm';
|
12
12
|
import { useSofa } from 'sofa-api';
|
13
|
+
import { MySqlDatabase } from 'drizzle-orm/mysql-core';
|
14
|
+
import { SingleStoreDatabase } from 'drizzle-orm/singlestore-core';
|
15
|
+
import { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core';
|
13
16
|
|
14
17
|
declare const pluginName = "ManualFiltersPlugin";
|
15
18
|
|
@@ -179,6 +182,8 @@ type GenericDrizzleDbTypeConstraints = {
|
|
179
182
|
}>) => any;
|
180
183
|
};
|
181
184
|
};
|
185
|
+
execute?: PgDatabase<any, any>["execute"] | MySqlDatabase<any, any>["execute"] | SingleStoreDatabase<any, any>["execute"] | undefined;
|
186
|
+
run?: BaseSQLiteDatabase<any, any>["run"];
|
182
187
|
} & DrizzleClient;
|
183
188
|
|
184
189
|
type CustomRumblePothosConfig = Omit<ConstructorParameters<typeof SchemaBuilder__default>[0], "smartSubscriptions" | "drizzle">;
|
@@ -217,6 +222,23 @@ type RumbleInput<UserContext extends Record<string, any>, DB extends GenericDriz
|
|
217
222
|
* @default 100
|
218
223
|
*/
|
219
224
|
defaultLimit?: number | undefined | null;
|
225
|
+
/**
|
226
|
+
* rumble supports fuzzy search for the query helpers. This enables the users of your API to search for entities via fuzzy search inputs.
|
227
|
+
* This currently only is supported by postgres databases and will fail if enabled on other dialects.
|
228
|
+
*
|
229
|
+
* Please note that this will install the pg_trgm extension on startup if your database does not have it already installed.
|
230
|
+
* https://www.postgresql.org/docs/current/pgtrgm.html
|
231
|
+
*/
|
232
|
+
search?: {
|
233
|
+
/**
|
234
|
+
* Whether search is enabled
|
235
|
+
*/
|
236
|
+
enabled?: boolean;
|
237
|
+
/**
|
238
|
+
* The threshold for cutting off non matching results. Defaults to 0.1. Lower = more results.
|
239
|
+
*/
|
240
|
+
threshold?: number;
|
241
|
+
} | undefined;
|
220
242
|
};
|
221
243
|
|
222
244
|
type NumberWhereInputArgument = {
|
@@ -332,7 +354,7 @@ declare const rumble: <UserContext extends Record<string, any>, DB extends Gener
|
|
332
354
|
readonly limit: any;
|
333
355
|
};
|
334
356
|
};
|
335
|
-
|
357
|
+
runtimeFilters: (action: Action) => (keyof DB["query"] extends infer T_4 extends keyof DB["query"] ? { [key_3 in T_4]: { [key_4 in Action]: Filter<UserContext, any>[]; }; } : never)[key_5][Action];
|
336
358
|
}; } : never;
|
337
359
|
};
|
338
360
|
/**
|
@@ -354,7 +376,7 @@ declare const rumble: <UserContext extends Record<string, any>, DB extends Gener
|
|
354
376
|
readonly limit: any;
|
355
377
|
};
|
356
378
|
};
|
357
|
-
|
379
|
+
runtimeFilters: (action: Action) => (keyof DB["query"] extends infer T_4 extends keyof DB["query"] ? { [key_3 in T_4]: { [key_4 in Action]: Filter<UserContext, any>[]; }; } : never)[key_5][Action];
|
358
380
|
}; } : never;
|
359
381
|
}>;
|
360
382
|
DrizzleRelations: DB["_"]["relations"];
|
@@ -441,7 +463,7 @@ declare const rumble: <UserContext extends Record<string, any>, DB extends Gener
|
|
441
463
|
readonly limit: any;
|
442
464
|
};
|
443
465
|
};
|
444
|
-
|
466
|
+
runtimeFilters: (action: Action) => (keyof DB["query"] extends infer T_5 extends keyof DB["query"] ? { [key_3 in T_5]: { [key_4 in Action]: Filter<UserContext, any>[]; }; } : never)[key_5][Action];
|
445
467
|
}; } : never;
|
446
468
|
}>;
|
447
469
|
DrizzleRelations: DB["_"]["relations"];
|
@@ -514,7 +536,7 @@ declare const rumble: <UserContext extends Record<string, any>, DB extends Gener
|
|
514
536
|
readonly limit: any;
|
515
537
|
};
|
516
538
|
};
|
517
|
-
|
539
|
+
runtimeFilters: (action: Action) => (keyof DB["query"] extends infer T_5 extends keyof DB["query"] ? { [key_3 in T_5]: { [key_4 in Action]: Filter<UserContext, any>[]; }; } : never)[key_5][Action];
|
518
540
|
}; } : never;
|
519
541
|
}>;
|
520
542
|
DrizzleRelations: DB["_"]["relations"];
|
@@ -566,7 +588,7 @@ declare const rumble: <UserContext extends Record<string, any>, DB extends Gener
|
|
566
588
|
readonly limit: any;
|
567
589
|
};
|
568
590
|
};
|
569
|
-
|
591
|
+
runtimeFilters: (action: Action) => (keyof DB["query"] extends infer T_5 extends keyof DB["query"] ? { [key_3 in T_5]: { [key_4 in Action]: Filter<UserContext, any>[]; }; } : never)[key_5][Action];
|
570
592
|
}; } : never;
|
571
593
|
}>;
|
572
594
|
DrizzleRelations: DB["_"]["relations"];
|
@@ -620,7 +642,7 @@ declare const rumble: <UserContext extends Record<string, any>, DB extends Gener
|
|
620
642
|
readonly limit: any;
|
621
643
|
};
|
622
644
|
};
|
623
|
-
|
645
|
+
runtimeFilters: (action: Action) => (keyof DB["query"] extends infer T_5 extends keyof DB["query"] ? { [key_3 in T_5]: { [key_4 in Action]: Filter<UserContext, any>[]; }; } : never)[key_5][Action];
|
624
646
|
}; } : never;
|
625
647
|
}>;
|
626
648
|
DrizzleRelations: DB["_"]["relations"];
|
@@ -702,7 +724,7 @@ declare const rumble: <UserContext extends Record<string, any>, DB extends Gener
|
|
702
724
|
readonly limit: any;
|
703
725
|
};
|
704
726
|
};
|
705
|
-
|
727
|
+
runtimeFilters: (action: Action) => (keyof DB["query"] extends infer T_6 extends keyof DB["query"] ? { [key_3 in T_6]: { [key_4 in Action]: Filter<UserContext, any>[]; }; } : never)[key_5][Action];
|
706
728
|
}; } : never;
|
707
729
|
}>;
|
708
730
|
DrizzleRelations: DB["_"]["relations"];
|
package/index.js
CHANGED
@@ -1,9 +1,9 @@
|
|
1
|
-
import {EnvelopArmorPlugin}from'@escape.tech/graphql-armor';import {useDisableIntrospection}from'@graphql-yoga/plugin-disable-introspection';import {merge,capitalize}from'es-toolkit';import {createYoga,createPubSub}from'graphql-yoga';import {useSofa}from'sofa-api';import {One,relationsFilterToSQL}from'drizzle-orm';import {toCamelCase}from'drizzle-orm/casing';import {PgEnumColumn}from'drizzle-orm/pg-core';import {singular
|
2
|
-
`,
|
3
|
-
`)}function
|
1
|
+
import {EnvelopArmorPlugin}from'@escape.tech/graphql-armor';import {useDisableIntrospection}from'@graphql-yoga/plugin-disable-introspection';import {merge,capitalize,cloneDeep}from'es-toolkit';import {createYoga,createPubSub}from'graphql-yoga';import {useSofa}from'sofa-api';import {sql,One,relationsFilterToSQL}from'drizzle-orm';import {toCamelCase}from'drizzle-orm/casing';import {PgEnumColumn,PgTable}from'drizzle-orm/pg-core';import {plural,singular}from'pluralize';import {MySqlTable}from'drizzle-orm/mysql-core';import {SQLiteTable}from'drizzle-orm/sqlite-core';import et,{BasePlugin}from'@pothos/core';import st from'@pothos/plugin-drizzle';import at,{subscribeOptionsFromIterator}from'@pothos/plugin-smart-subscriptions';import {JSONResolver,DateResolver,DateTimeISOResolver}from'graphql-scalars';function Y(e){return typeof e=="object"&&e!==null}function Z(e,n){throw new Error("Unexpected invariant triggered.")}var Ie=/\r\n|[\n\r]/g;function Q(e,n){let r=0,u=1;for(let i of e.body.matchAll(Ie)){if(typeof i.index=="number"||Z(),i.index>=n)break;r=i.index+i[0].length,u+=1;}return {line:u,column:n+1-r}}function te(e){return $(e.source,Q(e.source,e.start))}function $(e,n){let r=e.locationOffset.column-1,u="".padStart(r)+e.body,i=n.line-1,t=e.locationOffset.line-1,s=n.line+t,m=n.line===1?r:0,a=n.column+m,c=`${e.name}:${s}:${a}
|
2
|
+
`,l=u.split(/\r\n|[\n\r]/g),b=l[i];if(b.length>120){let o=Math.floor(a/80),C=a%80,y=[];for(let d=0;d<b.length;d+=80)y.push(b.slice(d,d+80));return c+ee([[`${s} |`,y[0]],...y.slice(1,o+1).map(d=>["|",d]),["|","^".padStart(C)],["|",y[o+1]]])}return c+ee([[`${s-1} |`,l[i-1]],[`${s} |`,b],["|","^".padStart(a)],[`${s+1} |`,l[i+1]]])}function ee(e){let n=e.filter(([u,i])=>i!==void 0),r=Math.max(...n.map(([u])=>u.length));return n.map(([u,i])=>u.padStart(r)+(i?" "+i:"")).join(`
|
3
|
+
`)}function Ne(e){let n=e[0];return n==null||"kind"in n||"length"in n?{nodes:n,source:e[1],positions:e[2],path:e[3],originalError:e[4],extensions:e[5]}:n}var L=class e extends Error{constructor(n,...r){var u,i,t;let{nodes:s,source:m,positions:a,path:c,originalError:l,extensions:b}=Ne(r);super(n),this.name="GraphQLError",this.path=c??void 0,this.originalError=l??void 0,this.nodes=ne(Array.isArray(s)?s:s?[s]:void 0);let o=ne((u=this.nodes)===null||u===void 0?void 0:u.map(y=>y.loc).filter(y=>y!=null));this.source=m??(o==null||(i=o[0])===null||i===void 0?void 0:i.source),this.positions=a??o?.map(y=>y.start),this.locations=a&&m?a.map(y=>Q(m,y)):o?.map(y=>Q(y.source,y.start));let C=Y(l?.extensions)?l?.extensions:void 0;this.extensions=(t=b??C)!==null&&t!==void 0?t:Object.create(null),Object.defineProperties(this,{message:{writable:true,enumerable:true},name:{enumerable:false},nodes:{enumerable:false},source:{enumerable:false},positions:{enumerable:false},originalError:{enumerable:false}}),l!=null&&l.stack?Object.defineProperty(this,"stack",{value:l.stack,writable:true,configurable:true}):Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:Error().stack,writable:true,configurable:true});}get[Symbol.toStringTag](){return "GraphQLError"}toString(){let n=this.message;if(this.nodes)for(let r of this.nodes)r.loc&&(n+=`
|
4
4
|
|
5
|
-
`+
|
5
|
+
`+te(r.loc));else if(this.source&&this.locations)for(let r of this.locations)n+=`
|
6
6
|
|
7
|
-
|
8
|
-
Please ensure that you use the enum at least once as a column of a table!`);u=h.enumValues;}else if(e){let s=Object.entries(t._.relations.schema).find(([h,o])=>o===e.config.enum);if(!s)throw new A(`Could not find enum in schema for ${e.name}!`);l=s[0],u=e.enumValues;}if(!l||!u)throw new A("Could not determine enum structure!");let m=y??`${capitalize(toCamelCase(l))}Enum`,a=r.get(m);return a||(a=n.enumType(m,{values:u}),r.set(m,a),a)}};var oe={paths:{"/webhook":{post:{operationId:"webhook_create",description:"Creates a webhook subscription.",tags:[],parameters:[],requestBody:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookCreateBody"}}}},responses:{200:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookDetailResponse"}}}}}}},"/webhook/{id}":{post:{operationId:"webhook_update",description:"Updates a webhook subscription.",parameters:[{name:"id",in:"path",description:"The ID of the webhook to update",required:true,schema:{type:"string"}}],requestBody:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookCreateBody"}}}},responses:{200:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookDetailResponse"}}}}}},delete:{operationId:"webhook_delete",description:"Removes a webhook subscription.",tags:[],parameters:[{name:"id",in:"path",description:"The ID of the webhook to delete",required:true,schema:{type:"string"}}],responses:{200:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookDetailResponse"}}}}}}}},components:{schemas:{WebhookCreateBody:{type:"object",properties:{subscription:{description:"The subscription to subscribe to. In many cases, these match the available query IDs without the '_query' suffix. E.g., 'findFirstUser_query' -> 'findFirstUser'. See the graphql schema for more details on what subscriptions are available.",type:"string"},variables:{description:"The variables to pass to the subscription.",type:"object"},url:{description:"The URL to send the webhook to.",type:"string"}}},WebhookDetailResponse:{type:"object",properties:{id:{description:"The ID of the webhook. Can be used as reference in update or delete calls.",type:"string"}}}}}};function G({sqlType:t,fieldName:n}){let r;if(["serial","int","integer","tinyint","smallint","mediumint"].includes(t)&&(r="Int"),["real","decimal","double","float"].includes(t)&&(r="Float"),["string","text","varchar","char","text(256)"].includes(t)&&(n&&(n.toLowerCase().endsWith("_id")||n.toLowerCase().endsWith("id"))?r="ID":r="String"),["uuid"].includes(t)&&(r="ID"),["boolean"].includes(t)&&(r="Boolean"),["timestamp","datetime"].includes(t)&&(r="DateTime"),["date"].includes(t)&&(r="Date"),["json"].includes(t)&&(r="JSON"),r!==void 0)return r;throw j(t,"SQL to GQL")}var ve=t=>typeof t!="object"?false:!!Object.keys(t).some(n=>["args","nullable","query","subscribe","description","type","resolve"].find(r=>r===n)),se=({db:t,schemaBuilder:n,makePubSubInstance:r,whereArgImplementer:p,orderArgImplementer:i,enumImplementer:e,abilityBuilder:y})=>({table:l,refName:u,readAction:m="read",adjust:a})=>{let g=N({db:t,tsName:l});Object.keys(g.primaryColumns).length===0&&console.warn(`Could not find primary key for ${l.toString()}. Cannot register subscriptions!`);let s=Object.values(g.primaryColumns)[0],{registerOnInstance:h}=r({table:l});return n.drizzleObject(l,{name:u??capitalize(l.toString()),subscribe:(o,b,f)=>{if(!s)return;let T=b[s.name];if(!T){console.warn(`Could not find primary key value for ${JSON.stringify(b)}. Cannot register subscription!`);return}h({instance:o,action:"updated",primaryKeyValue:T});},applyFilters:y?.z_registeredFilters?.[l]?.[m],fields:o=>{let b=g.columns,f=(S,d,x)=>{let c=G({sqlType:S,fieldName:d});switch(c){case "Int":return o.exposeInt(d,{nullable:x});case "String":return o.exposeString(d,{nullable:x});case "Boolean":return o.exposeBoolean(d,{nullable:x});case "Date":return o.field({type:"Date",resolve:R=>R[d],nullable:x});case "DateTime":return o.field({type:"DateTime",resolve:R=>R[d],nullable:x});case "Float":return o.exposeFloat(d,{nullable:x});case "ID":return o.exposeID(d,{nullable:x});case "JSON":return o.field({type:"JSON",resolve:R=>R[d],nullable:x});default:throw new A(`Unsupported object type ${c} for column ${d}`)}},T=new Map,C=a?.(new Proxy(o,{get:(S,d)=>typeof S[d]!="function"||d==="arg"||d==="builder"||d==="graphqlKind"||d==="kind"||d==="listRef"||d==="table"||d==="typename"||d==="variant"||d.toString().startsWith("boolean")||d.toString().startsWith("float")||d.toString().startsWith("id")||d.toString().startsWith("int")||d.toString().startsWith("string")||d.toString().startsWith("expose")?S[d]:(...x)=>{let c=S[d](...x),R=x.find(ve);if(!R)throw new A("Expected config object to be passed to adjust field");return T.set(c,{params:x,creatorFunction:S[d],configObject:R}),c}}))??{},D=Object.entries(b).reduce((S,[d,x])=>{if(C[d]){let{params:c,creatorFunction:R,configObject:P}=T.get(C[d]);return typeof P.nullable!="boolean"&&(P.nullable=!x.notNull),C[d]=R.bind(o)(...c),S}if(W(x)){let c=e({enumColumn:x});S[d]=o.field({type:c,resolve:R=>R[d],nullable:!x.notNull});}else S[d]=f(x.getSQLType(),d,!x.notNull);return S},{}),I=Object.entries(g.relations??{}).reduce((S,[d,x])=>{let c=N({db:t,table:x.targetTable}),R=p({dbName:c.dbName}),P=i({dbName:c.dbName}),w=r({table:c.tsName}),F=false,z=true,B="many";x instanceof One&&(z=false,F=x.optional,B="single");let U=(E,Q)=>{w.registerOnInstance({instance:E,action:"created"}),w.registerOnInstance({instance:E,action:"removed"});};if(C[d]){let{params:E,creatorFunction:Q,configObject:O}=T.get(C[d]);return typeof O.nullable!="boolean"&&(O.nullable=F),typeof O.subscribe!="function"&&(O.subscribe=U),C[d]=Q.bind(o)(...E),S}return S[d]=o.relation(d,{args:{where:o.arg({type:R,required:false}),orderBy:o.arg({type:P,required:false}),...z?{offset:o.arg.int({required:false}),limit:o.arg.int({required:false})}:{}},subscribe:U,nullable:F,query:(E,Q)=>{E=JSON.parse(JSON.stringify(E));let O=Q.abilities[c.tsName].filter(m,{inject:{where:E.where,limit:E.limit}}).query[B];return E.offset&&(O.offset=E.offset),E.orderBy&&(O.orderBy=E.orderBy),O}}),S},{});return {...D,...I,...C}}})};var ze=t=>`${capitalize(toCamelCase(t.toString()))}OrderInputArgument`,ae=({db:t,schemaBuilder:n})=>{let r=new Map,p=v(()=>n.enumType("SortingParameter",{values:["asc","desc"]})),i=({table:e,refName:y,dbName:l})=>{let u=N({db:t,dbName:l,tsName:e}),m=y??ze(u.tsName),a=r.get(m);return a||(a=n.inputType(m,{fields:s=>{let h=Object.entries(u.columns).reduce((b,[f,T])=>(b[f]=s.field({type:p(),required:false}),b),{}),o=Object.entries(u.relations??{}).reduce((b,[f,T])=>{let C=N({db:t,table:T.targetTable}),D=i({dbName:C.dbName});return b[f]=s.field({type:D,required:false}),b},{});return {...h,...o}}}),r.set(m,a),a)};return i};var qe="RUMBLE_SUBSCRIPTION_NOTIFICATION",ke="REMOVED",we="UPDATED",Le="CREATED",ue=({subscriptions:t,db:n})=>{let r=t?createPubSub(...t):createPubSub();return {pubsub:r,makePubSubInstance:({table:i})=>{function e({action:y,tableName:l,primaryKeyValue:u}){let m;switch(y){case "created":m=Le;break;case "removed":m=ke;break;case "updated":m=we;break;default:throw new Error(`Unknown action: ${y}`)}return `${qe}/${l}${u?`/${u}`:""}/${m}`}return {registerOnInstance({instance:y,action:l,primaryKeyValue:u}){let m=e({tableName:i.toString(),action:l,primaryKeyValue:u});y.register(m);},created(){let y=e({tableName:i.toString(),action:"created"});return r.publish(y)},removed(y){let l=e({tableName:i.toString(),action:"removed"});return r.publish(l)},updated(y){let u=(Array.isArray(y)?y:[y]).map(a=>e({tableName:i.toString(),action:"updated",primaryKeyValue:a})),m=Array.from(new Set(u));for(let a of m)r.publish(a);}}}}};var pe=({db:t,schemaBuilder:n,whereArgImplementer:r,orderArgImplementer:p,makePubSubInstance:i})=>({table:e,readAction:y="read",listAction:l="read"})=>{let u=r({table:e}),m=p({table:e}),a=N({db:t,tsName:e}),g=Object.values(a.primaryColumns)[0],{registerOnInstance:s}=i({table:e});return n.queryFields(h=>({[plural(e.toString())]:h.drizzleField({type:[e],nullable:false,smartSubscription:true,subscribe:(o,b,f,T,C)=>{s({instance:o,action:"created"}),s({instance:o,action:"removed"});},args:{where:h.arg({type:u,required:false}),orderBy:h.arg({type:m,required:false}),limit:h.arg.int({required:false}),offset:h.arg.int({required:false})},resolve:(o,b,f,T,C)=>{f=JSON.parse(JSON.stringify(f));let D=T.abilities[e].filter(l,f.where||f.limit||f.offset?{inject:{where:f.where,limit:f.limit}}:void 0).query.many;f.offset&&(D.offset=f.offset),f.orderBy&&(D.orderBy=f.orderBy);let I=o(D);return D.columns&&(I.columns=D.columns),t.query[e].findMany(I)}}),[singular(e.toString())]:h.drizzleField({type:e,nullable:false,smartSubscription:true,args:{id:h.arg.id({required:true})},resolve:(o,b,f,T,C)=>{f=JSON.parse(JSON.stringify(f));let D=T.abilities[e].filter(y,{inject:{where:{[g.name]:f.id}}}).query.single,I=o(D);return D.columns&&(I.columns=D.columns),t.query[e].findFirst(I).then(K)}})}))};var ce="ManualFiltersPlugin",ye=ce,me="applyFilters",M=class extends BasePlugin{wrapResolve(n,r){return async(p,i,e,y)=>{let l,u=r?.type;if(u.kind==="List"?l=u.type?.ref.currentConfig.pothosOptions[me]:u.kind==="Object"&&(l=u.ref.currentConfig.pothosOptions[me]),!l||!Array.isArray(l)||l.length===0)return n(p,i,e,y);let m=await n(p,i,e,y),a=Array.isArray(m)?m:[m],g=Array.isArray(l)?l:[l],s=await Z({filters:g,entities:a,context:e});return Array.isArray(m)?s:s[0]??null}}};je.registerPlugin(ce,M);var Ke=t=>`${capitalize(toCamelCase(t.toString()))}WhereInputArgument`,de=({db:t,schemaBuilder:n,enumImplementer:r})=>{let p=new Map,i=({table:e,refName:y,dbName:l})=>{let u=N({db:t,dbName:l,tsName:e}),m=y??Ke(u.tsName),a=p.get(m);return a||(a=n.inputType(m,{fields:s=>{let h=(f,T)=>{let C=G({sqlType:f,fieldName:T});switch(C){case "Int":return s.field({type:"IntWhereInputArgument"});case "String":return s.field({type:"StringWhereInputArgument"});case "Boolean":return s.boolean({required:false});case "Date":return s.field({type:"DateWhereInputArgument"});case "DateTime":return s.field({type:"DateWhereInputArgument"});case "Float":return s.field({type:"FloatWhereInputArgument"});case "ID":return s.id({required:false});case "JSON":return s.field({type:"JSON",required:false});default:throw new A(`Unsupported argument type ${C} for column ${f}`)}},o=Object.entries(u.columns).reduce((f,[T,C])=>{if(W(C)){let D=r({enumColumn:C});f[T]=s.field({type:D,required:false});}else f[T]=h(C.getSQLType(),T);return f},{}),b=Object.entries(u.relations??{}).reduce((f,[T,C])=>{let D=N({db:t,table:C.targetTable}),I=i({dbName:D.dbName});return f[T]=s.field({type:I,required:false}),f},{});return {...o,...b}}}),p.set(m,a),a)};return i};function fe(t){let n=t.inputRef("IntWhereInputArgument").implement({fields:e=>({eq:e.int(),ne:e.int(),gt:e.int(),gte:e.int(),lt:e.int(),lte:e.int(),in:e.intList(),notIn:e.intList(),like:e.string(),ilike:e.string(),notLike:e.string(),notIlike:e.string(),isNull:e.boolean(),isNotNull:e.boolean(),arrayOverlaps:e.intList(),arrayContained:e.intList(),arrayContains:e.intList(),AND:e.field({type:[n]}),OR:e.field({type:[n]}),NOT:e.field({type:n})})}),r=t.inputRef("FloatWhereInputArgument").implement({fields:e=>({eq:e.float(),ne:e.float(),gt:e.float(),gte:e.float(),lt:e.float(),lte:e.float(),in:e.floatList(),notIn:e.floatList(),like:e.string(),ilike:e.string(),notLike:e.string(),notIlike:e.string(),isNull:e.boolean(),isNotNull:e.boolean(),arrayOverlaps:e.floatList(),arrayContained:e.floatList(),arrayContains:e.floatList(),AND:e.field({type:[r]}),OR:e.field({type:[r]}),NOT:e.field({type:r})})}),p=t.inputRef("StringWhereInputArgument").implement({fields:e=>({eq:e.string(),ne:e.string(),gt:e.string(),gte:e.string(),lt:e.string(),lte:e.string(),in:e.stringList(),notIn:e.stringList(),like:e.string(),ilike:e.string(),notLike:e.string(),notIlike:e.string(),isNull:e.boolean(),isNotNull:e.boolean(),arrayOverlaps:e.stringList(),arrayContained:e.stringList(),arrayContains:e.stringList(),AND:e.field({type:[p]}),OR:e.field({type:[p]}),NOT:e.field({type:p})})}),i=t.inputRef("DateWhereInputArgument").implement({fields:e=>({eq:e.field({type:"Date"}),ne:e.field({type:"Date"}),gt:e.field({type:"Date"}),gte:e.field({type:"Date"}),lt:e.field({type:"Date"}),lte:e.field({type:"Date"}),in:e.field({type:["Date"]}),notIn:e.field({type:["Date"]}),like:e.string(),ilike:e.string(),notLike:e.string(),notIlike:e.string(),isNull:e.boolean(),isNotNull:e.boolean(),arrayOverlaps:e.field({type:["Date"]}),arrayContained:e.field({type:["Date"]}),arrayContains:e.field({type:["Date"]}),AND:e.field({type:[i]}),OR:e.field({type:[i]}),NOT:e.field({type:i})})});}var ge=({db:t,disableDefaultObjects:n,pubsub:r,pothosConfig:p})=>{let i=new je({...p,plugins:[ye,Me,$e,...p?.plugins??[]],drizzle:{client:t,relations:t._.relations,getTableConfig(e){return {columns:Object.values(e[Symbol.for("drizzle:Columns")]),primaryKeys:Object.values(e[Symbol.for("drizzle:Columns")]).filter(y=>y.primary)}}},smartSubscriptions:{...subscribeOptionsFromIterator((e,y)=>r.subscribe(e))}});return i.addScalarType("JSON",JSONResolver),i.addScalarType("Date",DateResolver),i.addScalarType("DateTime",DateTimeISOResolver),fe(i),n?.query||i.queryType({}),n?.subscription||i.subscriptionType({}),n?.mutation||i.mutationType({}),{schemaBuilder:i}};var it=t=>{t.actions||(t.actions=["read","update","delete"]),t.defaultLimit===void 0&&(t.defaultLimit=100);let n=ne(t),r=re({...t,abilityBuilder:n}),{makePubSubInstance:p,pubsub:i}=ue({...t}),{schemaBuilder:e}=ge({...t,pubsub:i}),y=ie({...t,schemaBuilder:e}),l=de({...t,schemaBuilder:e,enumImplementer:y}),u=ae({...t,schemaBuilder:e}),m=se({...t,schemaBuilder:e,makePubSubInstance:p,whereArgImplementer:l,orderArgImplementer:u,enumImplementer:y,abilityBuilder:n}),a=pe({...t,schemaBuilder:e,whereArgImplementer:l,orderArgImplementer:u,makePubSubInstance:p}),g=v(()=>e.toSchema());return {abilityBuilder:n,schemaBuilder:e,createYoga:o=>{let b=o?.enableApiDocs??process?.env?.NODE_ENV==="development"??false;return createYoga({...o,graphiql:b,plugins:[...o?.plugins??[],...b?[]:[useDisableIntrospection(),EnvelopArmorPlugin()]].filter(Boolean),schema:g(),context:r})},createSofa:o=>(o.openAPI&&merge(o.openAPI,oe),useSofa({...o,schema:g(),context:r})),object:m,whereArg:l,orderArg:u,query:a,pubsub:p,enum_:y}};export{A as RumbleError,k as RumbleErrorSafe,K as assertFindFirstExists,Ce as assertFirstEntryExists,De as mapNullFieldsToUndefined,it as rumble};//# sourceMappingURL=index.js.map
|
7
|
+
`+$(this.source,r);return n}toJSON(){let n={message:this.message};return this.locations!=null&&(n.locations=this.locations),this.path!=null&&(n.path=this.path),this.extensions!=null&&Object.keys(this.extensions).length>0&&(n.extensions=this.extensions),n}};function ne(e){return e===void 0||e.length===0?void 0:e}var A=class extends Error{constructor(n){super(n),this.name="RumbleError";}},k=class extends L{};var V=e=>{if(!e)throw new k("Value not found but required (findFirst)");return e},Pe=e=>{let n=e.at(0);if(!n)throw new k("Value not found but required (firstEntry)");return n},re=async({filters:e,entities:n,context:r})=>(await Promise.all(e.map(u=>u({context:r,entities:n})))).reduce((u,i)=>(u.push(...i),u),[]);function ve(e){return Object.fromEntries(Object.entries(e).map(([n,r])=>[n,r===null?void 0:r]))}function z(e){let n,r=false;return ()=>(r||(n=e(),r=true),n)}var G=(e,n)=>new A(`RumbleError: Unknown SQL type '${e}'. Please open an issue (https://github.com/m1212e/rumble/issues) so it can be added. (${n})`);function ie(e){if(["serial","int","integer","tinyint","smallint","mediumint"].includes(e))return {value1:1,value2:2};if(["real","decimal","double","float"].includes(e))return {value1:1.1,value2:2.2};if(["string","text","varchar","char","text(256)"].includes(e))return {value1:"a",value2:"b"};if(["uuid"].includes(e))return {value1:"fba31870-5528-42d7-b27e-2e5ee657aea5",value2:"fc65db81-c2d1-483d-8a25-a30e2cf6e02d"};if(["boolean"].includes(e))return {value1:true,value2:false};if(["timestamp","datetime"].includes(e))return {value1:new Date(2022,1,1),value2:new Date(2022,1,2)};if(["date"].includes(e))return {value1:new Date(2022,1,1),value2:new Date(2022,1,2)};if(["json"].includes(e))return {value1:{a:1},value2:{b:2}};throw G(e,"Distinct")}var M=Symbol.for("drizzle:Name"),oe=Symbol.for("drizzle:Columns");function P({dbName:e,tsName:n,table:r,db:u}){let i=r;if(n&&(i=u._.relations.schema[n]),e&&(i=Object.values(u._.relations.schema).find(t=>t[M]===e)),!i)throw new A(`Could not find schema for ${JSON.stringify({tsName:n,dbName:e,table:r?.[M]}).toString()}`);return {tableSchema:i,columns:i[oe],get primaryColumns(){return Object.entries(i[oe]).filter(([t,s])=>s.primary).reduce((t,[s,m])=>(t[s]=m,t),{})},relations:u._.relations.config[n],dbName:i[M],get tsName(){return Object.entries(u._.relations.schema).find(([t,s])=>s===i).at(0)}}}function Oe(e){return typeof e!="function"}function Fe(e){return typeof e=="function"&&e.constructor.name!=="AsyncFunction"}var se=({db:e,actions:n,defaultLimit:r})=>{let u={},i={},t={},s=m=>{for(let a of n)t[m]||(t[m]={}),t[m][a]||(t[m][a]=[]);return {allow:a=>{let c=i[m];c||(c={},i[m]=c);let l=Array.isArray(a)?a:[a];for(let b of l){let o=c[b];o||(o="unspecified",c[b]=o);}return {when:b=>{for(let o of l)c[o]==="unspecified"&&(c[o]=[]),c[o].push(b);}}},filter:a=>{let c=Array.isArray(a)?a:[a];return {by:l=>{for(let b of c)t[m][b].push(l);}}}}};for(let m of Object.keys(e.query))u[m]=s(m);return {...u,z_registeredQueryFilters:i,z_registeredFilters:t,z_buildWithUserContext:m=>{let a={},c=l=>({filter:(b,o)=>{let C=p=>{let x=z(()=>{if(!(!p?.where&&!o?.inject?.where)){if(o?.inject?.where&&p?.where)return {AND:[p?.where,o?.inject?.where]};if(o?.inject?.where&&!p?.where)return o?.inject?.where;if(!o?.inject?.where&&p?.where)return p?.where;!o?.inject?.where&&p?.where;}}),R=z(()=>{let N=x();if(!N)return;let j=P({tsName:l,db:e});return relationsFilterToSQL(j.tableSchema,N)}),q=z(()=>{let N=p?.limit??r;return o?.inject?.limit&&(!N||N>o.inject.limit)&&(N=o.inject.limit),p?.limit&&(!N||p.limit>N)&&(N=p.limit),N??void 0}),w=z(()=>{if(!(!p?.columns&&!o?.inject?.columns))return {...p?.columns,...o?.inject?.columns}}),O={query:{single:{get where(){return x()},columns:w()},many:{get where(){return x()},columns:w(),get limit(){return q()}}},sql:{get where(){return R()},columns:w(),get limit(){return q()}}};return w()||(delete O.sql.columns,delete O.query.many.columns,delete O.query.single.columns),O},y=()=>{let p=P({db:e,tsName:l});if(Object.keys(p.primaryColumns).length===0)throw new A(`No primary key found for entity ${l.toString()}`);let x=Object.values(p.primaryColumns)[0],R=ie(x.getSQLType());return {where:{AND:[{[x.name]:R.value1},{[x.name]:R.value2}]}}},d=i?.[l]?.[b];if(d==="unspecified")return C();d||(d=[y()]);let h=d.filter(Oe),S=d.filter(Fe).map(p=>p(m)),g=S.some(p=>p==="allow"),T=[...h,...S].filter(p=>p!==void 0).filter(p=>p!=="allow");!g&&T.length===0&&(T=[y()]);let v;for(let p of T)p?.limit&&(v===void 0||p.limit>v)&&(v=p.limit);let I;for(let p of [...T,o?.inject])p?.columns&&(I===void 0?I=p.columns:I={...I,...p.columns});let D=g?[]:T.filter(p=>p?.where).map(p=>p.where),f=D.length>0?{OR:D}:void 0;return C({where:f,columns:I,limit:v})},runtimeFilters:b=>t[l][b]});for(let l of Object.keys(e.query))a[l]=c(l);return a}}};var ae=({context:e,abilityBuilder:n})=>async r=>{let u=e?await e(r):{};return {...u,abilities:n.z_buildWithUserContext(u)}};function W(e){return e instanceof PgEnumColumn}var le=({db:e,schemaBuilder:n})=>{let r=new Map;return ({tsName:i,enumColumn:t,refName:s})=>{let m,a;if(i){let o=e._.relations.schema[i];m=i.toString();let C=Object.values(e._.relations.schema).filter(y=>typeof y=="object").map(y=>Object.values(y[Symbol.for("drizzle:Columns")])).flat(2).find(y=>y.config?.enum===o);if(!C)throw new A(`Could not find applied enum column for ${i.toString()}.
|
8
|
+
Please ensure that you use the enum at least once as a column of a table!`);a=C.enumValues;}else if(t){let o=Object.entries(e._.relations.schema).find(([C,y])=>y===t.config.enum);if(!o)throw new A(`Could not find enum in schema for ${t.name}!`);m=o[0],a=t.enumValues;}if(!m||!a)throw new A("Could not determine enum structure!");let c=s??`${capitalize(toCamelCase(m))}Enum`,l=r.get(c);return l||(l=n.enumType(c,{values:a}),r.set(c,l),l)}};var ue={paths:{"/webhook":{post:{operationId:"webhook_create",description:"Creates a webhook subscription.",tags:[],parameters:[],requestBody:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookCreateBody"}}}},responses:{200:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookDetailResponse"}}}}}}},"/webhook/{id}":{post:{operationId:"webhook_update",description:"Updates a webhook subscription.",parameters:[{name:"id",in:"path",description:"The ID of the webhook to update",required:true,schema:{type:"string"}}],requestBody:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookCreateBody"}}}},responses:{200:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookDetailResponse"}}}}}},delete:{operationId:"webhook_delete",description:"Removes a webhook subscription.",tags:[],parameters:[{name:"id",in:"path",description:"The ID of the webhook to delete",required:true,schema:{type:"string"}}],responses:{200:{content:{"application/json":{schema:{$ref:"#/components/schemas/WebhookDetailResponse"}}}}}}}},components:{schemas:{WebhookCreateBody:{type:"object",properties:{subscription:{description:"The subscription to subscribe to. In many cases, these match the available query IDs without the '_query' suffix. E.g., 'findFirstUser_query' -> 'findFirstUser'. See the graphql schema for more details on what subscriptions are available.",type:"string"},variables:{description:"The variables to pass to the subscription.",type:"object"},url:{description:"The URL to send the webhook to.",type:"string"}}},WebhookDetailResponse:{type:"object",properties:{id:{description:"The ID of the webhook. Can be used as reference in update or delete calls.",type:"string"}}}}}};function _({sqlType:e,fieldName:n}){let r;if(["serial","int","integer","tinyint","smallint","mediumint"].includes(e)&&(r="Int"),["real","decimal","double","float"].includes(e)&&(r="Float"),["string","text","varchar","char","text(256)"].includes(e)&&(n&&(n.toLowerCase().endsWith("_id")||n.toLowerCase().endsWith("id"))?r="ID":r="String"),["uuid"].includes(e)&&(r="ID"),["boolean"].includes(e)&&(r="Boolean"),["timestamp","datetime"].includes(e)&&(r="DateTime"),["date"].includes(e)&&(r="Date"),["json"].includes(e)&&(r="JSON"),r!==void 0)return r;throw G(e,"SQL to GQL")}function je(e){let n=new Set;for(let u of Object.values(e))typeof u=="object"&&(u instanceof PgTable?n.add("postgres"):u instanceof MySqlTable?n.add("mysql"):u instanceof SQLiteTable&&n.add("sqlite"));let r=Array.from(n);if(r.length===1)return r[0];throw r.length===0?new Error("No tables found in schema, could not determine dialect"):new Error(`Multiple dialects found in schema: ${r.join(", ")}`)}function pe(e){return je(e._.relations.schema)==="postgres"}async function ce(e){if(!pe(e)){console.info("Database dialect is not compatible with search, skipping search initialization.");return}await e.execute(sql`CREATE EXTENSION IF NOT EXISTS pg_trgm;`);}function K({search:e,args:n,tableSchema:r,abilities:u}){if(e?.enabled&&n.search&&n.search.length>0){let i=cloneDeep(n.orderBy);n.orderBy=s=>{let m=sql.join(Object.entries(i??{}).map(([b,o])=>{if(o==="asc")return sql`${s[b]} ASC`;if(o==="desc")return sql`${s[b]} DESC`;throw new Error(`Invalid value ${o} for orderBy`)}),sql.raw(", ")),a=u.query.many.columns?Object.entries(r.columns).filter(([b,o])=>u.query.many.columns[b]):Object.entries(r.columns),c=sql`GREATEST(${sql.join(a.map(([b,o])=>sql`similarity(${s[b]}::TEXT, ${n.search})`),sql.raw(", "))}) DESC`;return i?sql.join([m,c],sql.raw(", ")):c};let t=cloneDeep(n.where);n.where={AND:[t??{},{RAW:s=>sql`GREATEST(${sql.join(Object.entries(r.columns).map(([m,a])=>sql`similarity(${s[m]}::TEXT, ${n.search})`),sql.raw(", "))}) > ${e.threshold??.1}`}]};}}var $e=e=>typeof e!="object"?false:!!Object.keys(e).some(n=>["args","nullable","query","subscribe","description","type","resolve"].find(r=>r===n)),ye=({db:e,search:n,schemaBuilder:r,makePubSubInstance:u,whereArgImplementer:i,orderArgImplementer:t,enumImplementer:s,abilityBuilder:m})=>({table:a,refName:c,readAction:l="read",adjust:b})=>{let o=P({db:e,tsName:a});Object.keys(o.primaryColumns).length===0&&console.warn(`Could not find primary key for ${a.toString()}. Cannot register subscriptions!`);let C=Object.values(o.primaryColumns)[0],{registerOnInstance:y}=u({table:a});return r.drizzleObject(a,{name:c??capitalize(a.toString()),subscribe:(d,h,S)=>{if(!C)return;let g=h[C.name];if(!g){console.warn(`Could not find primary key value for ${JSON.stringify(h)}. Cannot register subscription!`);return}y({instance:d,action:"updated",primaryKeyValue:g});},applyFilters:m?.z_registeredFilters?.[a]?.[l],fields:d=>{let h=o.columns,S=(D,f,p)=>{let x=_({sqlType:D,fieldName:f});switch(x){case "Int":return d.exposeInt(f,{nullable:p});case "String":return d.exposeString(f,{nullable:p});case "Boolean":return d.exposeBoolean(f,{nullable:p});case "Date":return d.field({type:"Date",resolve:R=>R[f],nullable:p});case "DateTime":return d.field({type:"DateTime",resolve:R=>R[f],nullable:p});case "Float":return d.exposeFloat(f,{nullable:p});case "ID":return d.exposeID(f,{nullable:p});case "JSON":return d.field({type:"JSON",resolve:R=>R[f],nullable:p});default:throw new A(`Unsupported object type ${x} for column ${f}`)}},g=new Map,T=b?.(new Proxy(d,{get:(D,f)=>typeof D[f]!="function"||f==="arg"||f==="builder"||f==="graphqlKind"||f==="kind"||f==="listRef"||f==="table"||f==="typename"||f==="variant"||f.toString().startsWith("boolean")||f.toString().startsWith("float")||f.toString().startsWith("id")||f.toString().startsWith("int")||f.toString().startsWith("string")||f.toString().startsWith("expose")?D[f]:(...p)=>{let x=D[f](...p),R=p.find($e);if(!R)throw new A("Expected config object to be passed to adjust field");return g.set(x,{params:p,creatorFunction:D[f],configObject:R}),x}}))??{},v=Object.entries(h).reduce((D,[f,p])=>{if(T[f]){let{params:x,creatorFunction:R,configObject:q}=g.get(T[f]);return typeof q.nullable!="boolean"&&(q.nullable=!p.notNull),T[f]=R.bind(d)(...x),D}if(W(p)){let x=s({enumColumn:p});D[f]=d.field({type:x,resolve:R=>R[f],nullable:!p.notNull});}else D[f]=S(p.getSQLType(),f,!p.notNull);return D},{}),I=Object.entries(o.relations??{}).reduce((D,[f,p])=>{let x=P({db:e,table:p.targetTable}),R=i({dbName:x.dbName}),q=t({dbName:x.dbName}),w=u({table:x.tsName}),O=false,N=true,j="many";p instanceof One&&(N=false,O=p.optional,j="single");let H=(E,U)=>{w.registerOnInstance({instance:E,action:"created"}),w.registerOnInstance({instance:E,action:"removed"});};if(T[f]){let{params:E,creatorFunction:U,configObject:F}=g.get(T[f]);return typeof F.nullable!="boolean"&&(F.nullable=O),typeof F.subscribe!="function"&&(F.subscribe=H),T[f]=U.bind(d)(...E),D}let X={where:d.arg({type:R,required:false}),orderBy:d.arg({type:q,required:false}),...N?{offset:d.arg.int({required:false}),limit:d.arg.int({required:false})}:{},search:d.arg.string({required:false})};return (!n?.enabled||!N)&&delete X.search,D[f]=d.relation(f,{args:X,subscribe:H,nullable:O,description:`Get the ${plural(x.tsName)} related to this ${singular(o.tsName)}.`,query:(E,U)=>{E=JSON.parse(JSON.stringify(E)),N&&K({search:n,args:E,tableSchema:x,abilities:U.abilities[x.tsName].filter(l)});let F=U.abilities[x.tsName].filter(l,{inject:{where:E.where,limit:E.limit}}).query[j];return E.offset&&(F.offset=E.offset),E.orderBy&&(F.orderBy=E.orderBy),F}}),D},{});return {...v,...I,...T}}})};var Je=e=>`${capitalize(toCamelCase(e.toString()))}OrderInputArgument`,de=({db:e,schemaBuilder:n})=>{let r=new Map,u=z(()=>n.enumType("SortingParameter",{values:["asc","desc"]})),i=({table:t,refName:s,dbName:m})=>{let a=P({db:e,dbName:m,tsName:t}),c=s??Je(a.tsName),l=r.get(c);return l||(l=n.inputType(c,{fields:o=>{let C=Object.entries(a.columns).reduce((d,[h,S])=>(d[h]=o.field({type:u(),required:false}),d),{}),y=Object.entries(a.relations??{}).reduce((d,[h,S])=>{let g=P({db:e,table:S.targetTable}),T=i({dbName:g.dbName});return d[h]=o.field({type:T,required:false}),d},{});return {...C,...y}}}),r.set(c,l),l)};return i};var He="RUMBLE_SUBSCRIPTION_NOTIFICATION",Xe="REMOVED",Ye="UPDATED",Ze="CREATED",be=({subscriptions:e,db:n})=>{let r=e?createPubSub(...e):createPubSub();return {pubsub:r,makePubSubInstance:({table:i})=>{function t({action:s,tableName:m,primaryKeyValue:a}){let c;switch(s){case "created":c=Ze;break;case "removed":c=Xe;break;case "updated":c=Ye;break;default:throw new Error(`Unknown action: ${s}`)}return `${He}/${m}${a?`/${a}`:""}/${c}`}return {registerOnInstance({instance:s,action:m,primaryKeyValue:a}){let c=t({tableName:i.toString(),action:m,primaryKeyValue:a});s.register(c);},created(){let s=t({tableName:i.toString(),action:"created"});return r.publish(s)},removed(s){let m=t({tableName:i.toString(),action:"removed"});return r.publish(m)},updated(s){let a=(Array.isArray(s)?s:[s]).map(l=>t({tableName:i.toString(),action:"updated",primaryKeyValue:l})),c=Array.from(new Set(a));for(let l of c)r.publish(l);}}}}};var Te=({db:e,schemaBuilder:n,search:r,whereArgImplementer:u,orderArgImplementer:i,makePubSubInstance:t})=>({table:s,readAction:m="read",listAction:a="read"})=>{let c=u({table:s}),l=i({table:s}),b=P({db:e,tsName:s}),o=Object.values(b.primaryColumns)[0],{registerOnInstance:C}=t({table:s});return n.queryFields(y=>{let d={where:y.arg({type:c,required:false}),orderBy:y.arg({type:l,required:false}),limit:y.arg.int({required:false}),offset:y.arg.int({required:false}),search:y.arg.string({required:false})};return r?.enabled||delete d.search,{[plural(s.toString())]:y.drizzleField({type:[s],nullable:false,smartSubscription:true,description:`List all ${plural(s.toString())}`,subscribe:(h,S,g,T,v)=>{C({instance:h,action:"created"}),C({instance:h,action:"removed"});},args:d,resolve:(h,S,g,T,v)=>{g=JSON.parse(JSON.stringify(g)),K({search:r,args:g,tableSchema:b,abilities:T.abilities[s].filter(a)});let I=T.abilities[s].filter(a,g.where||g.limit||g.offset?{inject:{where:g.where,limit:g.limit}}:void 0).query.many;g.offset&&(I.offset=g.offset),g.orderBy&&(I.orderBy=g.orderBy);let D=h(I);return I.columns&&(D.columns=I.columns),e.query[s].findMany(D)}}),[singular(s.toString())]:y.drizzleField({type:s,nullable:false,smartSubscription:true,description:`Get a single ${singular(s.toString())}`,args:{id:y.arg.id({required:true})},resolve:(h,S,g,T,v)=>{g=JSON.parse(JSON.stringify(g));let I=T.abilities[s].filter(m,{inject:{where:{[o.name]:g.id}}}).query.single,D=h(I);return I.columns&&(D.columns=I.columns),e.query[s].findFirst(D).then(V)}})}})};var De="ManualFiltersPlugin",Ce=De,xe="applyFilters",J=class extends BasePlugin{wrapResolve(n,r){return async(u,i,t,s)=>{let m,a=r?.type;if(a.kind==="List"?m=a.type?.ref.currentConfig.pothosOptions[xe]:a.kind==="Object"&&(m=a.ref.currentConfig.pothosOptions[xe]),!m||!Array.isArray(m)||m.length===0)return n(u,i,t,s);let c=await n(u,i,t,s),l=Array.isArray(c)?c:[c],b=Array.isArray(m)?m:[m],o=await re({filters:b,entities:l,context:t});return Array.isArray(c)?o:o[0]??null}}};et.registerPlugin(De,J);var it=e=>`${capitalize(toCamelCase(e.toString()))}WhereInputArgument`,Se=({db:e,schemaBuilder:n,enumImplementer:r})=>{let u=new Map,i=({table:t,refName:s,dbName:m})=>{let a=P({db:e,dbName:m,tsName:t}),c=s??it(a.tsName),l=u.get(c);return l||(l=n.inputType(c,{fields:o=>{let C=(h,S)=>{let g=_({sqlType:h,fieldName:S});switch(g){case "Int":return o.field({type:"IntWhereInputArgument"});case "String":return o.field({type:"StringWhereInputArgument"});case "Boolean":return o.boolean({required:false});case "Date":return o.field({type:"DateWhereInputArgument"});case "DateTime":return o.field({type:"DateWhereInputArgument"});case "Float":return o.field({type:"FloatWhereInputArgument"});case "ID":return o.id({required:false});case "JSON":return o.field({type:"JSON",required:false});default:throw new A(`Unsupported argument type ${g} for column ${h}`)}},y=Object.entries(a.columns).reduce((h,[S,g])=>{if(W(g)){let T=r({enumColumn:g});h[S]=o.field({type:T,required:false});}else h[S]=C(g.getSQLType(),S);return h},{}),d=Object.entries(a.relations??{}).reduce((h,[S,g])=>{let T=P({db:e,table:g.targetTable}),v=i({dbName:T.dbName});return h[S]=o.field({type:v,required:false}),h},{});return {...y,...d}}}),u.set(c,l),l)};return i};function Re(e){let n=e.inputRef("IntWhereInputArgument").implement({fields:t=>({eq:t.int(),ne:t.int(),gt:t.int(),gte:t.int(),lt:t.int(),lte:t.int(),in:t.intList(),notIn:t.intList(),like:t.string(),ilike:t.string(),notLike:t.string(),notIlike:t.string(),isNull:t.boolean(),isNotNull:t.boolean(),arrayOverlaps:t.intList(),arrayContained:t.intList(),arrayContains:t.intList(),AND:t.field({type:[n]}),OR:t.field({type:[n]}),NOT:t.field({type:n})})}),r=e.inputRef("FloatWhereInputArgument").implement({fields:t=>({eq:t.float(),ne:t.float(),gt:t.float(),gte:t.float(),lt:t.float(),lte:t.float(),in:t.floatList(),notIn:t.floatList(),like:t.string(),ilike:t.string(),notLike:t.string(),notIlike:t.string(),isNull:t.boolean(),isNotNull:t.boolean(),arrayOverlaps:t.floatList(),arrayContained:t.floatList(),arrayContains:t.floatList(),AND:t.field({type:[r]}),OR:t.field({type:[r]}),NOT:t.field({type:r})})}),u=e.inputRef("StringWhereInputArgument").implement({fields:t=>({eq:t.string(),ne:t.string(),gt:t.string(),gte:t.string(),lt:t.string(),lte:t.string(),in:t.stringList(),notIn:t.stringList(),like:t.string(),ilike:t.string(),notLike:t.string(),notIlike:t.string(),isNull:t.boolean(),isNotNull:t.boolean(),arrayOverlaps:t.stringList(),arrayContained:t.stringList(),arrayContains:t.stringList(),AND:t.field({type:[u]}),OR:t.field({type:[u]}),NOT:t.field({type:u})})}),i=e.inputRef("DateWhereInputArgument").implement({fields:t=>({eq:t.field({type:"Date"}),ne:t.field({type:"Date"}),gt:t.field({type:"Date"}),gte:t.field({type:"Date"}),lt:t.field({type:"Date"}),lte:t.field({type:"Date"}),in:t.field({type:["Date"]}),notIn:t.field({type:["Date"]}),like:t.string(),ilike:t.string(),notLike:t.string(),notIlike:t.string(),isNull:t.boolean(),isNotNull:t.boolean(),arrayOverlaps:t.field({type:["Date"]}),arrayContained:t.field({type:["Date"]}),arrayContains:t.field({type:["Date"]}),AND:t.field({type:[i]}),OR:t.field({type:[i]}),NOT:t.field({type:i})})});}var Ae=({db:e,disableDefaultObjects:n,pubsub:r,pothosConfig:u})=>{let i=new et({...u,plugins:[Ce,st,at,...u?.plugins??[]],drizzle:{client:e,relations:e._.relations,getTableConfig(t){return {columns:Object.values(t[Symbol.for("drizzle:Columns")]),primaryKeys:Object.values(t[Symbol.for("drizzle:Columns")]).filter(s=>s.primary)}}},smartSubscriptions:{...subscribeOptionsFromIterator((t,s)=>r.subscribe(t))}});return i.addScalarType("JSON",JSONResolver),i.addScalarType("Date",DateResolver),i.addScalarType("DateTime",DateTimeISOResolver),Re(i),n?.query||i.queryType({}),n?.subscription||i.subscriptionType({}),n?.mutation||i.mutationType({}),{schemaBuilder:i}};var gt=e=>{e.actions||(e.actions=["read","update","delete"]),e.defaultLimit===void 0&&(e.defaultLimit=100),e.search?.enabled&&ce(e.db);let n=se(e),r=ae({...e,abilityBuilder:n}),{makePubSubInstance:u,pubsub:i}=be({...e}),{schemaBuilder:t}=Ae({...e,pubsub:i}),s=le({...e,schemaBuilder:t}),m=Se({...e,schemaBuilder:t,enumImplementer:s}),a=de({...e,schemaBuilder:t}),c=ye({...e,schemaBuilder:t,makePubSubInstance:u,whereArgImplementer:m,orderArgImplementer:a,enumImplementer:s,abilityBuilder:n}),l=Te({...e,schemaBuilder:t,whereArgImplementer:m,orderArgImplementer:a,makePubSubInstance:u}),b=z(()=>t.toSchema());return {abilityBuilder:n,schemaBuilder:t,createYoga:y=>{let d=y?.enableApiDocs??process?.env?.NODE_ENV==="development"??false;return createYoga({...y,graphiql:d,plugins:[...y?.plugins??[],...d?[]:[useDisableIntrospection(),EnvelopArmorPlugin()]].filter(Boolean),schema:b(),context:r})},createSofa:y=>(y.openAPI&&merge(y.openAPI,ue),useSofa({...y,schema:b(),context:r})),object:c,whereArg:m,orderArg:a,query:l,pubsub:u,enum_:s}};export{A as RumbleError,k as RumbleErrorSafe,V as assertFindFirstExists,Pe as assertFirstEntryExists,ve as mapNullFieldsToUndefined,gt as rumble};//# sourceMappingURL=index.js.map
|
9
9
|
//# sourceMappingURL=index.js.map
|