@m1212e/rumble 0.3.11 → 0.3.13
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 +150 -44
- package/index.cjs +2 -2
- package/index.cjs.map +1 -1
- package/index.d.cts +19 -13
- package/index.d.ts +19 -13
- package/index.js +2 -2
- package/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
@@ -3,7 +3,7 @@ rumble is a combined ability and graphql builder built around [drizzle](https://
|
|
3
3
|
|
4
4
|
> Please note that drizzle hasn't reached a full stable release yet and, as shown in the warning [here](https://pothos-graphql.dev/docs/plugins/drizzle), this is not stable yet.
|
5
5
|
|
6
|
-
> Using rumble and reading these docs requires some basic knowledge about the above mentioned tools. If you feel stuck, please make sure to familiarize yourself with those first!
|
6
|
+
> Using rumble and reading these docs requires some basic knowledge about the above mentioned tools. If you feel stuck, please make sure to familiarize yourself with those first! Especially familiarity with pothos and its drizzle plugin are very helpful!
|
7
7
|
|
8
8
|
> This is still in a very early stage and needs more testing. Please feel free to report everything you find/your feedback via the issues/discussion section of this repo!
|
9
9
|
|
@@ -21,72 +21,178 @@ import * as schema from "./db/schema";
|
|
21
21
|
import { rumble } from "@m1212e/rumble";
|
22
22
|
|
23
23
|
export const db = drizzle(
|
24
|
-
|
25
|
-
|
24
|
+
"postgres://postgres:postgres@localhost:5432/postgres",
|
25
|
+
{ schema }
|
26
26
|
);
|
27
27
|
|
28
28
|
const { abilityBuilder } = rumble({ db });
|
29
29
|
```
|
30
30
|
> If the creation of a drizzle instance with the schema definition seems unfamiliar to you, please see their excellent [getting started guide](https://orm.drizzle.team/docs/get-started)
|
31
31
|
|
32
|
-
|
33
|
-
|
32
|
+
The rumble creator returns some functions which you can use to implement your api. The concepts rumble uses are described in the following sections:
|
33
|
+
|
34
|
+
## Abilities
|
35
|
+
Abilities are the way you define who can do things in your app. You can imagine an ability as `a thing that is allowed`. Abilities can be very wide and applied in general or precisely and narrowly scoped to very specific conditions. You can create abilities with the `abilityBuilder` function returned from the rumble initiator. There are three kinds of abilities:
|
36
|
+
|
37
|
+
### Wildcard
|
38
|
+
Wildcard abilities allow everyone to do a thing. The `allow` call takes a single `action` or an array of `action` strings. You can customize the available actions when calling the rumble initializer.
|
34
39
|
```ts
|
40
|
+
// everyone can read posts
|
35
41
|
abilityBuilder.posts.allow("read");
|
42
|
+
|
43
|
+
// everyone can read and write posts
|
44
|
+
abilityBuilder.posts.allow(["read", "write"]);
|
36
45
|
```
|
37
|
-
|
46
|
+
|
47
|
+
### Condition Object
|
48
|
+
Condition object abilities allow a thing under a certain, fixed condition which does not change. __Note, that the object has the same type as a drizzle query call.__
|
38
49
|
```ts
|
50
|
+
// everyone can read published posts
|
39
51
|
abilityBuilder.posts.allow("read").when({
|
40
|
-
|
52
|
+
where: eq(schema.posts.published, true),
|
41
53
|
});
|
42
54
|
```
|
43
|
-
The `when` call accepts a variety of restrictions which have different effects. E.g. you could also set a limit on how many results can be queried at a time. The accepted type is the same as the drizzle query api (e.g. the `findMany` call) which will be relevant later.
|
44
55
|
|
45
|
-
|
46
|
-
|
56
|
+
### Condition Function
|
57
|
+
Condition functions are functions that return condition objects. They are called each time an evaluation takes place and can dynamically decide if something should be allowed or not. They receive the request context as a parameter to decide e.g. based on cookies or headers if something is allowed or not.
|
47
58
|
```ts
|
48
|
-
|
49
|
-
|
50
|
-
|
51
|
-
|
52
|
-
|
53
|
-
// here you could access the cookies of the
|
54
|
-
// request object and extract the user ID or some
|
55
|
-
// other form of permissions
|
56
|
-
return {
|
57
|
-
userId: 2, // we mock this for now
|
58
|
-
};
|
59
|
-
},
|
60
|
-
});
|
59
|
+
// only the author can update posts
|
60
|
+
abilityBuilder.posts
|
61
|
+
.allow(["update", "delete"])
|
62
|
+
.when(({ userId }) => ({ where: eq(schema.posts.authorId, userId) }));
|
63
|
+
|
61
64
|
```
|
62
|
-
|
65
|
+
|
66
|
+
### Applying abilities
|
67
|
+
As you might have noticed, abilities resolve around drizzle query filters. This means, that we can use them to query the database with filters applied that directly restrict what the user is allowed to see, update and retrieve.
|
63
68
|
```ts
|
64
|
-
|
65
|
-
|
66
|
-
.
|
69
|
+
schemaBuilder.queryFields((t) => {
|
70
|
+
return {
|
71
|
+
findManyPosts: t.drizzleField({
|
72
|
+
type: [PostRef],
|
73
|
+
resolve: (query, root, args, ctx, info) => {
|
74
|
+
return db.query.posts.findMany(
|
75
|
+
// here we apply our filter
|
76
|
+
query(ctx.abilities.posts.filter("read")),
|
77
|
+
);
|
78
|
+
},
|
79
|
+
}),
|
80
|
+
};
|
81
|
+
});
|
82
|
+
```
|
67
83
|
|
84
|
+
## Context & Configuration
|
85
|
+
The `rumble` initiator offers various configuration options which you can pass. Most importantly, the `context` provider function which creates the request context that is passed to your abilities and resolvers.
|
86
|
+
```ts
|
87
|
+
rumble({
|
88
|
+
db,
|
89
|
+
context(request) {
|
90
|
+
return {
|
91
|
+
// here you could instead read some cookies or HTTP headers to retrieve an actual userId
|
92
|
+
userId: 2,
|
93
|
+
};
|
94
|
+
},
|
95
|
+
});
|
68
96
|
```
|
69
97
|
|
70
|
-
|
71
|
-
|
72
|
-
|
98
|
+
## Helpers
|
99
|
+
Rumble offers various helpers to make it easy and fast to implement your api. Ofcourse you can write your api by hand using the provided `schemaBuilder` from the rumble initiator, but since this might get repetitive, the provided helpers automate a lot of this work for you while also automatically applying the concepts of rumble directly into your api.
|
100
|
+
|
101
|
+
### arg
|
102
|
+
`arg` is a helper to implement query arguments for filtering the results of a query for certain results. In many cases you would implement arguments for a query with something as `matchUsername: t.arg.string()` which is supposed to restrict the query to users which have that username. The arg helper implements such a filter tailored to the specific entity which you then can directly pass on to the database query.
|
73
103
|
```ts
|
74
|
-
const
|
75
|
-
|
76
|
-
|
77
|
-
|
78
|
-
|
79
|
-
|
80
|
-
|
81
|
-
|
82
|
-
|
104
|
+
const {
|
105
|
+
inputType,
|
106
|
+
transformArgumentToQueryCondition,
|
107
|
+
} = arg({
|
108
|
+
tableName: "posts",
|
109
|
+
});
|
110
|
+
|
111
|
+
schemaBuilder.queryFields((t) => {
|
112
|
+
return {
|
113
|
+
findManyPostsFiltered: t.drizzleField({
|
114
|
+
type: [PostRef],
|
115
|
+
args: {
|
116
|
+
// here we set our generated type as type for the where argument
|
117
|
+
where: t.arg({ type: inputType }),
|
118
|
+
},
|
119
|
+
resolve: (query, root, args, ctx, info) => {
|
120
|
+
return db.query.posts.findMany(
|
121
|
+
query(
|
122
|
+
// here we apply the ability filter
|
123
|
+
ctx.abilities.users.filter("read", {
|
124
|
+
// we can inject one time filters into the permission filter
|
125
|
+
inject: {
|
126
|
+
// here we transform the args into a drizzle filter
|
127
|
+
where: transformArgumentToQueryCondition(args.where),
|
128
|
+
},
|
129
|
+
}),
|
130
|
+
),
|
131
|
+
);
|
132
|
+
},
|
83
133
|
}),
|
134
|
+
};
|
135
|
+
});
|
136
|
+
```
|
137
|
+
|
138
|
+
### object
|
139
|
+
`object` is a helper to implement an object with relations. Don't worry about abilities, they are automatically applied. The helper returns the object reference which you can use in the rest of your api, for an example on how to use a type, see the above code snippet (`type: [PostRef],`).
|
140
|
+
```ts
|
141
|
+
const UserRef = object({
|
142
|
+
tableName: "users",
|
84
143
|
});
|
85
144
|
```
|
86
|
-
In the above object definition we tell pothos to expose the id and content so the fields will be just passed along from out database results and we define a relation to the posts author. We also restrict which author can be read. If the user which sends this request is not the author of a post, they cannot see the author and the request will fail. The `ctx.abilities.users.filter("read")` call simply injects the filter we defined in the abilities earlier and therefore restricts what can be returned.
|
87
145
|
|
88
|
-
###
|
89
|
-
|
146
|
+
### query
|
147
|
+
The `query` helper is even simpler. It implements a `findFirst` and `findMany` query for the specified entity.
|
148
|
+
```ts
|
149
|
+
query({
|
150
|
+
tableName: "users",
|
151
|
+
});
|
152
|
+
|
153
|
+
```
|
154
|
+
|
155
|
+
### pubsub
|
156
|
+
In case you want to use subscriptions, `rumble` has got you covered! The rumble helpers all use the `smart subscriptions plugin` from `pothos`. The `pubsub` helper lets you easily hook into the subscription notification logic.
|
157
|
+
```ts
|
158
|
+
const { updated, created, removed } = pubsub({
|
159
|
+
tableName: "users",
|
160
|
+
});
|
161
|
+
```
|
162
|
+
Now just call the functions whenever your application does the respective action and your subscriptions will get notified:
|
163
|
+
```ts
|
164
|
+
updateUsernameHandler() => {
|
165
|
+
await db.updateTheUsername();
|
166
|
+
// the pubsub function
|
167
|
+
updated(user.id);
|
168
|
+
}
|
169
|
+
// or if creating
|
170
|
+
createUserHandler() => {
|
171
|
+
await db.createTheUser();
|
172
|
+
// the pubsub function
|
173
|
+
created();
|
174
|
+
}
|
175
|
+
```
|
176
|
+
All `query` and `object` helper implementations will automatically update and work right out of the box, no additional config needed!
|
177
|
+
|
178
|
+
> The rumble initiator lets you configure the subscription notifiers in case you want to use an external service like redis for your pubsub notifications instead of the internal default one
|
179
|
+
|
180
|
+
### enum_
|
181
|
+
The `enum_` helper is a little different to the others, as it will get called internally automatically if another helper like `object` or `arg` detects an enum field. In most cases you should be good without calling it manually but in case you would like to have a reference to an enum object, you can get it from this helper.
|
182
|
+
```ts
|
183
|
+
const enumRef = enum_({
|
184
|
+
enumVariableName: "moodEnum",
|
185
|
+
});
|
186
|
+
```
|
187
|
+
> The enum parameter allows for various other fields to use to reference an enum. This is largely due to how this is used internally. Because of the way how drizzle handles enums, we are not able to provide type safety with enums. In case you actually need to use it, the above way is the recommended one to use it.
|
188
|
+
|
189
|
+
## Running the server
|
190
|
+
In case you directly want to run a server from your rumble instance, you can do so by using the `createYoga` function. It returns a graphql `yoga` instance which can be used to provide a graphql api in [a multitude of ways](https://the-guild.dev/graphql/yoga-server/docs/integrations/z-other-environments).
|
191
|
+
```ts
|
192
|
+
import { createServer } from "node:http";
|
193
|
+
const server = createServer(createYoga());
|
194
|
+
server.listen(3000, () => {
|
195
|
+
console.info("Visit http://localhost:3000/graphql");
|
196
|
+
});
|
90
197
|
|
91
|
-
|
92
|
-
rumble supports subscriptions right out of the box. When using the rumble helpers, you basically get subscriptions for free, no additional work required!
|
198
|
+
```
|
package/index.cjs
CHANGED
@@ -1,3 +1,3 @@
|
|
1
|
-
'use strict';var graphqlYoga=require('graphql-yoga'),drizzleOrm=require('drizzle-orm'),casing=require('drizzle-orm/casing'),ee=require('@pothos/core'),te=require('@pothos/plugin-drizzle'),ne=require('@pothos/plugin-smart-subscriptions'),graphqlScalars=require('graphql-scalars');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ee__default=/*#__PURE__*/_interopDefault(ee);var te__default=/*#__PURE__*/_interopDefault(te);var ne__default=/*#__PURE__*/_interopDefault(ne);var T=class extends Error{constructor(t){super(t),this.name="RumbleError";}};var I=(e,t)=>new T(`RumbleError: Unknown SQL type '${e}'. Please open an issue (https://github.com/m1212e/rumble/issues) so it can be added. (${t})`);function q(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 I(e,"Distinct")}function K(e){return typeof e!="function"}function V(e){return typeof e=="function"&&e.constructor.name!=="AsyncFunction"}var N=({db:e})=>{let t=e._.schema,b={},r={},o=i=>({allow:x=>{let m=r[i];m||(m={},r[i]=m);let p=Array.isArray(x)?x:[x];for(let l of p){let s=m[l];s||(s="wildcard",m[l]=s);}return {when:l=>{for(let s of p)m[s]==="wildcard"&&(m[s]=[]),m[s].push(l);}}}});for(let i of Object.keys(e.query))b[i]=o(i);return {...b,registeredConditions:r,buildWithUserContext:i=>{let x={},m=p=>({filter:(l,s)=>{let a=r[p];a||(a={});let D=a[l];if(D==="wildcard")return {where:void 0,columns:void 0,limit:void 0,...s?.inject};let g=()=>{let f=t[p].primaryKey.at(0);if(!f)throw new T(`No primary key found for entity ${p.toString()}`);let U=q(f.getSQLType());return {where:drizzleOrm.and(drizzleOrm.eq(f,U.value1),drizzleOrm.eq(f,U.value2))}};(!a||!D)&&(D=[g()]);let d=D.filter(K),S=D.filter(V).map(f=>f(i)),u=[...d,...S];u.filter(f=>f!==void 0).length===0&&u.push(g());let n;for(let f of u)f?.limit&&(n===void 0||f.limit>n)&&(n=f.limit);s?.inject?.limit&&n<s.inject.limit&&(n=s.inject.limit);let c;for(let f of [...u,s?.inject??{}])f?.columns&&(c===void 0?c=f.columns:c={...c,...f.columns});let y=u.filter(f=>f?.where).map(f=>f?.where),R=y.length>0?drizzleOrm.or(...y):void 0;return s?.inject?.where&&(R=R?drizzleOrm.and(R,s.inject.where):s.inject.where),{where:R,columns:c,limit:n}}});for(let p of Object.keys(e.query))x[p]=m(p);return x}}};var Q=({context:e,abilityBuilder:t})=>async b=>{let r=e?await e(b):{};return {...r,abilities:t.buildWithUserContext(r)}};function C(e){return String(e).charAt(0).toUpperCase()+String(e).slice(1)}function E(e){let t=B(e);return t.enumValues!==void 0&&t.enumName!==void 0&&typeof t.enumName=="string"&&Array.isArray(t.enumValues)}function B(e){return e.enum??e}var O=({db:e,schemaBuilder:t})=>{let b=new Map;return ({enumVariableName:o,name:i,enumValues:x,enumName:m})=>{let p=e._.fullSchema,l;if(o?l=p[o]:x?l=Object.values(p).filter(E).map(B).find(g=>g.enumValues===x):m&&(l=Object.values(p).filter(E).map(B).find(g=>g.enumName===m)),!l)throw new T(`Could not determine enum structure! (${String(o)}, ${x}, ${m})`);let s=i??`${C(casing.toCamelCase(l.enumName.toString()))}Enum`,a=b.get(s);return a||(a=t.enumType(s,{values:l.enumValues}),b.set(s,a),a)}};function A(e){let t;if(["serial","int","integer","tinyint","smallint","mediumint"].includes(e)&&(t="Int"),["real","decimal","double","float"].includes(e)&&(t="Float"),["string","text","varchar","char","text(256)"].includes(e)&&(t="String"),["uuid"].includes(e)&&(t="ID"),["boolean"].includes(e)&&(t="Boolean"),["timestamp","datetime"].includes(e)&&(t="DateTime"),["date"].includes(e)&&(t="Date"),["json"].includes(e)&&(t="JSON"),t!==void 0)return t;throw I(e,"SQL to GQL")}var J="RUMBLE_SUBSCRIPTION_NOTIFICATION",W="REMOVED",Y="UPDATED",X="CREATED";function v({action:e,tableName:t,primaryKeyValue:b}){let r;switch(e){case "created":r=X;break;case "removed":r=W;break;case "updated":r=Y;break;default:throw new Error(`Unknown action: ${e}`)}return `${J}/${t}${b?`/${b}`:""}/${r}`}var F=({subscriptions:e})=>{let t=e?graphqlYoga.createPubSub(...e):graphqlYoga.createPubSub();return {pubsub:t,makePubSubInstance:({tableName:r})=>({registerOnInstance({instance:o,action:i,primaryKeyValue:x}){let m=v({tableName:r.toString(),action:i,primaryKeyValue:x});o.register(m);},created(){let o=v({tableName:r.toString(),action:"created"});return t.publish(o)},removed(o){let i=v({tableName:r.toString(),action:"removed"});return t.publish(i)},updated(o){let i=v({tableName:r.toString(),action:"updated",primaryKeyValue:o});return t.publish(i)}})}};var L=({db:e,schemaBuilder:t,makePubSubInstance:b,argImplementer:r,enumImplementer:o})=>({tableName:i,name:x,readAction:m="read"})=>{let p=e._.schema[i];if(!p)throw new T(`Could not find schema for ${i.toString()} (object)`);let l=p.primaryKey.at(0)?.name;l||console.warn(`Could not find primary key for ${i.toString()}. Cannot register subscriptions!`);let{registerOnInstance:s}=b({tableName:i});return t.drizzleObject(i,{name:x??C(i.toString()),subscribe:(a,D,g)=>{if(!l)return;let d=D[l];if(!d){console.warn(`Could not find primary key value for ${JSON.stringify(D)}. Cannot register subscription!`);return}s({instance:a,action:"updated",primaryKeyValue:d});},fields:a=>{let D=(S,u,n)=>{let c=A(S);switch(c){case "Int":return a.exposeInt(u,{nullable:n});case "String":return a.exposeString(u,{nullable:n});case "Boolean":return a.exposeBoolean(u,{nullable:n});case "Date":return a.field({type:"Date",resolve:y=>y[u],nullable:n});case "DateTime":return a.field({type:"DateTime",resolve:y=>y[u],nullable:n});case "Float":return a.exposeFloat(u,{nullable:n});case "ID":return a.exposeID(u,{nullable:n});case "JSON":return a.field({type:"JSON",resolve:y=>y[u],nullable:n});default:throw new T(`Unsupported object type ${c} for column ${u}`)}},g=Object.entries(p.columns).reduce((S,[u,n])=>{if(E(n)){let c=B(n),y=o({enumName:c.enumName});S[u]=a.field({type:y,resolve:R=>R[u],nullable:!n.notNull});}else S[u]=D(n.getSQLType(),u,!n.notNull);return S},{}),d=Object.entries(p.relations).reduce((S,[u,n])=>{let{inputType:c,transformArgumentToQueryCondition:y}=r({tableName:n.referencedTableName,nativeTableName:n.referencedTableName}),R=false;return n instanceof drizzleOrm.One&&(R=!n.isNullable),S[u]=a.relation(u,{args:{where:a.arg({type:c,required:false})},nullable:R,query:(h,f)=>f.abilities[n.referencedTableName].filter(m,{inject:{where:y(h.where)}})}),S},{});return {...g,...d}}})};var z=e=>{if(!e)throw new T("Value not found but required (findFirst)");return e},Z=e=>{let t=e.at(0);if(!t)throw new T("Value not found but required (firstEntry)");return t};var j=({db:e,schemaBuilder:t,argImplementer:b,makePubSubInstance:r})=>({tableName:o,readAction:i="read",listAction:x="read"})=>{let m=e._.schema[o];if(!m)throw new T(`Could not find schema for ${o.toString()} (query)`);m.primaryKey.at(0)?.name||console.warn(`Could not find primary key for ${o.toString()}. Cannot register subscriptions!`);let{inputType:l,transformArgumentToQueryCondition:s}=b({tableName:o}),{registerOnInstance:a}=r({tableName:o});return t.queryFields(D=>({[`findMany${C(o.toString())}`]:D.drizzleField({type:[o],nullable:false,smartSubscription:true,subscribe:(g,d,S,u,n)=>{a({instance:g,action:"created"}),a({instance:g,action:"removed"});},args:{where:D.arg({type:l,required:false})},resolve:(g,d,S,u,n)=>{let c=u.abilities[o].filter(i,{inject:{where:s(S.where)}}),y=g(c);return c.columns&&(y.columns=c.columns),e.query[o].findMany(y)}}),[`findFirst${C(o.toString())}`]:D.drizzleField({type:o,nullable:false,smartSubscription:true,args:{where:D.arg({type:l,required:false})},resolve:(g,d,S,u,n)=>{let c=u.abilities[o].filter(i,{inject:{where:s(S.where)}}),y=g(c);return c.columns&&(y.columns=c.columns),e.query[o].findFirst(y).then(z)}})}))};var G=({db:e,disableDefaultObjects:t,pubsub:b})=>{let r=new ee__default.default({plugins:[te__default.default,ne__default.default],drizzle:{client:e},smartSubscriptions:{...ne.subscribeOptionsFromIterator((o,i)=>b.subscribe(o))}});return r.addScalarType("JSON",graphqlScalars.JSONResolver),r.addScalarType("Date",graphqlScalars.DateResolver),r.addScalarType("DateTime",graphqlScalars.DateTimeISOResolver),t?.query||r.queryType({}),t?.subscription||r.subscriptionType({}),t?.mutation||r.mutationType({}),{schemaBuilder:r}};var _=({db:e,schemaBuilder:t,enumImplementer:b})=>{let r=new Map;return ({tableName:i,name:x,nativeTableName:m})=>{let p=e._.schema[i];if(m){let D=Object.values(e._.schema).find(g=>g.dbName===m);D&&(p=D);}if(!p)throw new T(`Could not find schema for ${i.toString()} (whereArg)`);let l=x??`${C(casing.toCamelCase(i.toString()))}WhereInputArgument`,s=r.get(l);return s||(s={inputType:t.inputType(l,{fields:d=>{let S=n=>{let c=A(n);switch(c){case "Int":return d.int({required:false});case "String":return d.string({required:false});case "Boolean":return d.boolean({required:false});case "Date":return d.field({type:"Date",required:false});case "DateTime":return d.field({type:"DateTime",required:false});case "Float":return d.float({required:false});case "ID":return d.id({required:false});case "JSON":return d.field({type:"JSON",required:false});default:throw new T(`Unsupported argument type ${c} for column ${n}`)}};return {...Object.entries(p.columns).reduce((n,[c,y])=>{if(E(y)){let R=B(y),h=b({enumName:R.enumName});n[c]=d.field({type:h,required:false});}else n[c]=S(y.getSQLType());return n},{})}}}),transformArgumentToQueryCondition:d=>{if(!d)return;let S=n=>{let c=p.columns[n],y=d[n];if(y)return drizzleOrm.eq(c,y)},u=Object.keys(p.columns).map(S);return drizzleOrm.and(...u)}},r.set(l,s),s)}};var pe=e=>{let t=N(e),b=Q({...e,abilityBuilder:t}),{makePubSubInstance:r,pubsub:o}=F({...e}),{schemaBuilder:i}=G({...e,pubsub:o}),x=O({...e,schemaBuilder:i}),m=_({...e,schemaBuilder:i,enumImplementer:x}),p=L({...e,schemaBuilder:i,makePubSubInstance:r,argImplementer:m,enumImplementer:x}),l=j({...e,schemaBuilder:i,argImplementer:m,makePubSubInstance:r});return {abilityBuilder:t,schemaBuilder:i,createYoga:a=>graphqlYoga.createYoga({...a,schema:i.toSchema(),context:b}),object:p,arg:m,query:l,pubsub:r,enum_:x}};
|
2
|
-
exports.RumbleError=
|
1
|
+
'use strict';var graphqlYoga=require('graphql-yoga'),drizzleOrm=require('drizzle-orm'),casing=require('drizzle-orm/casing'),ee=require('@pothos/core'),te=require('@pothos/plugin-drizzle'),ne=require('@pothos/plugin-smart-subscriptions'),graphqlScalars=require('graphql-scalars');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ee__default=/*#__PURE__*/_interopDefault(ee);var te__default=/*#__PURE__*/_interopDefault(te);var ne__default=/*#__PURE__*/_interopDefault(ne);var h=class extends Error{constructor(t){super(t),this.name="RumbleError";}};var P=(e,t)=>new h(`RumbleError: Unknown SQL type '${e}'. Please open an issue (https://github.com/m1212e/rumble/issues) so it can be added. (${t})`);function U(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 P(e,"Distinct")}function K(e){return typeof e!="function"}function V(e){return typeof e=="function"&&e.constructor.name!=="AsyncFunction"}var N=({db:e})=>{let t=e._.schema,C={},s={},r=o=>({allow:d=>{let m=s[o];m||(m={},s[o]=m);let p=Array.isArray(d)?d:[d];for(let l of p){let i=m[l];i||(i="wildcard",m[l]=i);}return {when:l=>{for(let i of p)m[i]==="wildcard"&&(m[i]=[]),m[i].push(l);}}}});for(let o of Object.keys(e.query))C[o]=r(o);return {...C,registeredConditions:s,buildWithUserContext:o=>{let d={},m=p=>({filter:(l,i)=>{let u=s[p];u||(u={});let b=u[l];if(b==="wildcard")return {where:i?.inject?.where,columns:i?.inject?.columns,limit:i?.inject?.limit};let x=()=>{let g=t[p].primaryKey.at(0);if(!g)throw new h(`No primary key found for entity ${p.toString()}`);let z=U(g.getSQLType());return {where:drizzleOrm.and(drizzleOrm.eq(g,z.value1),drizzleOrm.eq(g,z.value2))}};(!u||!b)&&(b=[x()]);let f=b.filter(K),D=b.filter(V).map(g=>g(o)),a=[...f,...D];a.filter(g=>g!==void 0).length===0&&a.push(x());let n;for(let g of a)g?.limit&&(n===void 0||g.limit>n)&&(n=g.limit);i?.inject?.limit&&n<i.inject.limit&&(n=i.inject.limit);let c;for(let g of [...a,i?.inject??{}])g?.columns&&(c===void 0?c=g.columns:c={...c,...g.columns});let y=a.filter(g=>g?.where).map(g=>g?.where),R=y.length>0?drizzleOrm.or(...y):void 0;return i?.inject?.where&&(R=R?drizzleOrm.and(R,i.inject.where):i.inject.where),{where:R,columns:c,limit:n}}});for(let p of Object.keys(e.query))d[p]=m(p);return d}}};var Q=({context:e,abilityBuilder:t})=>async C=>{let s=e?await e(C):{};return {...s,abilities:t.buildWithUserContext(s)}};function T(e){return String(e).charAt(0).toUpperCase()+String(e).slice(1)}function B(e){let t=S(e);return t.enumValues!==void 0&&t.enumName!==void 0&&typeof t.enumName=="string"&&Array.isArray(t.enumValues)}function S(e){return e.enum??e}var O=({db:e,schemaBuilder:t})=>{let C=new Map;return ({enumVariableName:r,name:o,enumValues:d,enumName:m})=>{let p=e._.fullSchema,l;if(r?l=p[r]:d?l=Object.values(p).filter(B).map(S).find(x=>x.enumValues===d):m&&(l=Object.values(p).filter(B).map(S).find(x=>x.enumName===m)),!l)throw new h(`Could not determine enum structure! (${String(r)}, ${d}, ${m})`);let i=o??`${T(casing.toCamelCase(l.enumName.toString()))}Enum`,u=C.get(i);return u||(u=t.enumType(i,{values:l.enumValues}),C.set(i,u),u)}};function I(e){let t;if(["serial","int","integer","tinyint","smallint","mediumint"].includes(e)&&(t="Int"),["real","decimal","double","float"].includes(e)&&(t="Float"),["string","text","varchar","char","text(256)"].includes(e)&&(t="String"),["uuid"].includes(e)&&(t="ID"),["boolean"].includes(e)&&(t="Boolean"),["timestamp","datetime"].includes(e)&&(t="DateTime"),["date"].includes(e)&&(t="Date"),["json"].includes(e)&&(t="JSON"),t!==void 0)return t;throw P(e,"SQL to GQL")}var J="RUMBLE_SUBSCRIPTION_NOTIFICATION",W="REMOVED",Y="UPDATED",X="CREATED";function A({action:e,tableName:t,primaryKeyValue:C}){let s;switch(e){case "created":s=X;break;case "removed":s=W;break;case "updated":s=Y;break;default:throw new Error(`Unknown action: ${e}`)}return `${J}/${t}${C?`/${C}`:""}/${s}`}var F=({subscriptions:e})=>{let t=e?graphqlYoga.createPubSub(...e):graphqlYoga.createPubSub();return {pubsub:t,makePubSubInstance:({tableName:s})=>({registerOnInstance({instance:r,action:o,primaryKeyValue:d}){let m=A({tableName:s.toString(),action:o,primaryKeyValue:d});r.register(m);},created(){let r=A({tableName:s.toString(),action:"created"});return t.publish(r)},removed(r){let o=A({tableName:s.toString(),action:"removed"});return t.publish(o)},updated(r){let o=A({tableName:s.toString(),action:"updated",primaryKeyValue:r});return t.publish(o)}})}};var L=({db:e,schemaBuilder:t,makePubSubInstance:C,argImplementer:s,enumImplementer:r})=>({tableName:o,name:d,readAction:m="read"})=>{let p=e._.schema[o];if(!p)throw new h(`Could not find schema for ${o.toString()} (object)`);let l=p.primaryKey.at(0)?.name;l||console.warn(`Could not find primary key for ${o.toString()}. Cannot register subscriptions!`);let{registerOnInstance:i}=C({tableName:o});return t.drizzleObject(o,{name:d??T(o.toString()),subscribe:(u,b,x)=>{if(!l)return;let f=b[l];if(!f){console.warn(`Could not find primary key value for ${JSON.stringify(b)}. Cannot register subscription!`);return}i({instance:u,action:"updated",primaryKeyValue:f});},fields:u=>{let b=(D,a,n)=>{let c=I(D);switch(c){case "Int":return u.exposeInt(a,{nullable:n});case "String":return u.exposeString(a,{nullable:n});case "Boolean":return u.exposeBoolean(a,{nullable:n});case "Date":return u.field({type:"Date",resolve:y=>y[a],nullable:n});case "DateTime":return u.field({type:"DateTime",resolve:y=>y[a],nullable:n});case "Float":return u.exposeFloat(a,{nullable:n});case "ID":return u.exposeID(a,{nullable:n});case "JSON":return u.field({type:"JSON",resolve:y=>y[a],nullable:n});default:throw new h(`Unsupported object type ${c} for column ${a}`)}},x=Object.entries(p.columns).reduce((D,[a,n])=>{if(B(n)){let c=S(n),y=r({enumName:c.enumName});D[a]=u.field({type:y,resolve:R=>R[a],nullable:!n.notNull});}else D[a]=b(n.getSQLType(),a,!n.notNull);return D},{}),f=Object.entries(p.relations).reduce((D,[a,n])=>{let{inputType:c,transformArgumentToQueryCondition:y}=s({tableName:n.referencedTableName,nativeTableName:n.referencedTableName}),R=false;return n instanceof drizzleOrm.One&&(R=!n.isNullable),D[a]=u.relation(a,{args:{where:u.arg({type:c,required:false})},nullable:R,query:(E,g)=>g.abilities[n.referencedTableName].filter(m,{inject:{where:y(E.where)}})}),D},{});return {...x,...f}}})};var v=e=>{if(!e)throw new h("Value not found but required (findFirst)");return e},Z=e=>{let t=e.at(0);if(!t)throw new h("Value not found but required (firstEntry)");return t};var j=({db:e,schemaBuilder:t,argImplementer:C,makePubSubInstance:s})=>({tableName:r,readAction:o="read",listAction:d="read"})=>{let m=e._.schema[r];if(!m)throw new h(`Could not find schema for ${r.toString()} (query)`);m.primaryKey.at(0)?.name||console.warn(`Could not find primary key for ${r.toString()}. Cannot register subscriptions!`);let{inputType:l,transformArgumentToQueryCondition:i}=C({tableName:r}),{registerOnInstance:u}=s({tableName:r});return t.queryFields(b=>({[`findMany${T(r.toString())}`]:b.drizzleField({type:[r],nullable:false,smartSubscription:true,subscribe:(x,f,D,a,n)=>{u({instance:x,action:"created"}),u({instance:x,action:"removed"});},args:{where:b.arg({type:l,required:false})},resolve:(x,f,D,a,n)=>{let c=a.abilities[r].filter(d,{inject:{where:i(D.where)}}),y=x(c);return c.columns&&(y.columns=c.columns),e.query[r].findMany(y)}}),[`findFirst${T(r.toString())}`]:b.drizzleField({type:r,nullable:false,smartSubscription:true,args:{where:b.arg({type:l,required:false})},resolve:(x,f,D,a,n)=>{let c=a.abilities[r].filter(o,{inject:{where:i(D.where)}}),y=x(c);return c.columns&&(y.columns=c.columns),e.query[r].findFirst(y).then(v)}})}))};var G=({db:e,disableDefaultObjects:t,pubsub:C,pothosConfig:s})=>{let r=new ee__default.default({plugins:[te__default.default,ne__default.default,...s?.plugins??[]],...s,drizzle:{client:e},smartSubscriptions:{...ne.subscribeOptionsFromIterator((o,d)=>C.subscribe(o))}});return r.addScalarType("JSON",graphqlScalars.JSONResolver),r.addScalarType("Date",graphqlScalars.DateResolver),r.addScalarType("DateTime",graphqlScalars.DateTimeISOResolver),t?.query||r.queryType({}),t?.subscription||r.subscriptionType({}),t?.mutation||r.mutationType({}),{schemaBuilder:r}};var _=({db:e,schemaBuilder:t,enumImplementer:C})=>{let s=new Map;return ({tableName:o,name:d,nativeTableName:m})=>{let p=e._.schema[o];if(m){let b=Object.values(e._.schema).find(x=>x.dbName===m);b&&(p=b);}if(!p)throw new h(`Could not find schema for ${o.toString()} (whereArg)`);let l=d??`${T(casing.toCamelCase(o.toString()))}WhereInputArgument`,i=s.get(l);return i||(i={inputType:t.inputType(l,{fields:f=>{let D=n=>{let c=I(n);switch(c){case "Int":return f.int({required:false});case "String":return f.string({required:false});case "Boolean":return f.boolean({required:false});case "Date":return f.field({type:"Date",required:false});case "DateTime":return f.field({type:"DateTime",required:false});case "Float":return f.float({required:false});case "ID":return f.id({required:false});case "JSON":return f.field({type:"JSON",required:false});default:throw new h(`Unsupported argument type ${c} for column ${n}`)}};return {...Object.entries(p.columns).reduce((n,[c,y])=>{if(B(y)){let R=S(y),E=C({enumName:R.enumName});n[c]=f.field({type:E,required:false});}else n[c]=D(y.getSQLType());return n},{})}}}),transformArgumentToQueryCondition:f=>{if(!f)return;let D=n=>{let c=p.columns[n],y=f[n];if(y)return drizzleOrm.eq(c,y)},a=Object.keys(p.columns).map(D);return drizzleOrm.and(...a)}},s.set(l,i),i)}};var pe=e=>{let t=N(e),C=Q({...e,abilityBuilder:t}),{makePubSubInstance:s,pubsub:r}=F({...e}),{schemaBuilder:o}=G({...e,pubsub:r}),d=O({...e,schemaBuilder:o}),m=_({...e,schemaBuilder:o,enumImplementer:d}),p=L({...e,schemaBuilder:o,makePubSubInstance:s,argImplementer:m,enumImplementer:d}),l=j({...e,schemaBuilder:o,argImplementer:m,makePubSubInstance:s});return {abilityBuilder:t,schemaBuilder:o,createYoga:u=>graphqlYoga.createYoga({...u,schema:o.toSchema(),context:C}),object:p,arg:m,query:l,pubsub:s,enum_:d}};
|
2
|
+
exports.RumbleError=h;exports.assertFindFirstExists=v;exports.assertFirstEntryExists=Z;exports.rumble=pe;//# sourceMappingURL=index.cjs.map
|
3
3
|
//# sourceMappingURL=index.cjs.map
|