ramdb2-cli 0.0.0-stage → 2.0.0-alpha.0
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/LICENSE +21 -0
- package/README.md +369 -2
- package/package.json +33 -4
- package/src/cli.js +124 -0
- package/src/convert.js +90 -0
- package/src/directives.js +42 -0
- package/src/generate/classes.js +292 -0
- package/src/generate/client.js +146 -0
- package/src/generate/invalidation.js +102 -0
- package/src/generate/operations.js +98 -0
- package/src/generate/typeDefs.js +39 -0
- package/src/generate.js +51 -0
- package/src/index.js +8 -0
- package/src/model.js +420 -0
- package/src/new.js +619 -0
- package/src/plantuml.js +71 -0
- package/src/query.js +159 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Emmanuel Leparquier
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,370 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ramdb2-cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**The command line of ramdb2**: it turns a GraphQL schema into the classes of a [ramdb2-core](https://www.npmjs.com/package/ramdb2-core) database
|
|
4
|
+
and the schema of a [ramdb2-server](https://www.npmjs.com/package/ramdb2-server) API, creates new projects, draws the data model and
|
|
5
|
+
queries a running server.
|
|
6
|
+
|
|
7
|
+
| Command | |
|
|
8
|
+
|---|---|
|
|
9
|
+
| [`generate`](#generate) | the classes, the GraphQL schema and the schema of the operations, from the preTypeDefs |
|
|
10
|
+
| [`client`](#client) | the classes of a ramdb2-client application, from the preTypeDefs of its server |
|
|
11
|
+
| [`new`](#new) | a project ready to start, on ramdb2 and ramdb2-server, with a web site if asked |
|
|
12
|
+
| [`plantuml`](#plantuml) | the entity-relationship diagram of the data model |
|
|
13
|
+
| [`query`](#query) | a GraphQL query to a server, with an authentication token managed for you |
|
|
14
|
+
| [`convert`](#convert) | a v1 preTypeDefs (annotations in the descriptions) converted to directives |
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
ramdb2-cli --help
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
```sh
|
|
21
|
+
npm install -g ramdb2-cli@alpha # or, without installing it: npx ramdb2-cli@alpha new my_project
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
All the ramdb2 packages share one version: a project created by `ramdb2-cli new` depends on the version of the
|
|
25
|
+
ramdb2-cli that created it. Node.js 22 or later.
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## generate
|
|
30
|
+
|
|
31
|
+
```sh
|
|
32
|
+
ramdb2-cli generate --schema schema/preTypeDefs.graphql --dest .
|
|
33
|
+
ramdb2-cli generate --schema schema/preTypeDefs.graphql --schema schema/types.graphql --dest .
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Several `--schema` files are read as one schema. In a project created by `ramdb2-cli new`: `npm run generate`.
|
|
37
|
+
|
|
38
|
+
### What it writes
|
|
39
|
+
|
|
40
|
+
| File | Content | Rewritten |
|
|
41
|
+
|---|---|---|
|
|
42
|
+
| `db/generated/<table>.js` | class `XxxBase`: fields, foreign keys, indexes, rules, default values, getters and setters, relations, computed fields, finders, invalidation code | at each generation |
|
|
43
|
+
| `db/extended/<table>.js` | class `Xxx extends XxxBase`: your business rules, computed fields and methods | never: created when missing |
|
|
44
|
+
| `db/index.js` | the extended classes, and `classes` for `store.register(...classes)` | at each generation |
|
|
45
|
+
| `schema/typeDefs.graphql` | the schema served by the API: without the directives (but `@sensitive`) nor the `@private` fields, with `id` and the foreign keys | at each generation |
|
|
46
|
+
| `schema/operations.graphql` | the `JSON` scalar, and for each type its input (with the `@sensitive` fields, without the `@private` ones), validation, query and list types, its queries and mutations | at each generation |
|
|
47
|
+
|
|
48
|
+
Never edit a generated file: the next generation would erase the change. Everything you write goes in
|
|
49
|
+
`db/extended`, and in your own schema files (`extend type Query { ... }`).
|
|
50
|
+
|
|
51
|
+
### The schema: the preTypeDefs
|
|
52
|
+
|
|
53
|
+
```graphql
|
|
54
|
+
enum Genre { NOVEL ESSAY }
|
|
55
|
+
|
|
56
|
+
"An author of books."
|
|
57
|
+
type Author @persistent @group(name: "LIBRARY") {
|
|
58
|
+
id: Int!
|
|
59
|
+
name: String! @index(type: FULLTEXT)
|
|
60
|
+
code: String! @pattern(regex: "^[A-Z]{2}$", message: "code must be 2 uppercase letters") @index
|
|
61
|
+
books: [Book!] @field(name: "idAuthor")
|
|
62
|
+
loanCount: Int! @computed(depends: ["books.loans"])
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
type Book @persistent @group(name: "LIBRARY") @index(fields: ["idAuthor", "title"]) {
|
|
66
|
+
id: Int!
|
|
67
|
+
author: Author!
|
|
68
|
+
sequel: Book
|
|
69
|
+
title: String! @index(type: FULLTEXT)
|
|
70
|
+
year: Int! @index(type: BTREE)
|
|
71
|
+
genre: Genre!
|
|
72
|
+
loans: [Loan!] @field(name: "idBook") @onDelete(action: RESTRICT)
|
|
73
|
+
authorName: String! @computed(depends: ["author.name"])
|
|
74
|
+
shelf: String! @transient
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
type Loan @persistent {
|
|
78
|
+
id: Int!
|
|
79
|
+
book: Book!
|
|
80
|
+
borrower: String!
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### Directives
|
|
85
|
+
|
|
86
|
+
The directives are declared by ramdb2-cli, not in your files. graphql-js checks every use: an unknown directive,
|
|
87
|
+
a directive in the wrong place, a missing or badly typed argument is an error.
|
|
88
|
+
|
|
89
|
+
| Directive | On | Arguments | Meaning |
|
|
90
|
+
|---|---|---|---|
|
|
91
|
+
| `@persistent` | type | | a ramdb2 table |
|
|
92
|
+
| `@group` | type | `name: String!` | package of the type in the diagram |
|
|
93
|
+
| `@index` | field | `type: MAP \| BTREE \| FULLTEXT = MAP`, `name: String`, `unique: Boolean` | an index on the field; `unique` (MAP only): no two objects with the same value |
|
|
94
|
+
| `@index` (repeatable) | type | `fields: [String!]!` (two or more), `name: String`, `unique: Boolean` | an index on several fields |
|
|
95
|
+
| `@field` | list | `name: String!` | the foreign key held by the other type |
|
|
96
|
+
| `@onDelete` | list | `action: CASCADE \| SET_ZERO \| RESTRICT \| NOTHING` | deletion policy of these objects |
|
|
97
|
+
| `@computed` | field | `depends: [String!]!` | a cached value, with the paths it depends on |
|
|
98
|
+
| `@pattern` | field | `regex: String!`, `message: String` | a validation rule |
|
|
99
|
+
| `@transient` | field | | a field of the API that is not stored |
|
|
100
|
+
| `@sensitive` | field | | its value is masked in the logs of ramdb2-server (`"[REDACTED]"`) |
|
|
101
|
+
| `@private` | field | | stored and read by your code, but absent from the API: neither read, written nor queried (a password hash). Not with `!` when it would be required, nor with a FULLTEXT index |
|
|
102
|
+
|
|
103
|
+
### How the fields are read
|
|
104
|
+
|
|
105
|
+
In a `@persistent` type, every field is stored, except `@computed` and `@transient` ones:
|
|
106
|
+
|
|
107
|
+
| Field | Becomes |
|
|
108
|
+
|---|---|
|
|
109
|
+
| scalar, enum, custom scalar | a stored field |
|
|
110
|
+
| `author: Author!` (a persistent type) | a relation: the foreign key `idAuthor` (`id` + the field name), required because of `!` |
|
|
111
|
+
| `books: [Book!] @field(name: "idAuthor")` | a list relation: the books whose `idAuthor` is this author |
|
|
112
|
+
| any other type, a list of scalars | an error, unless `@computed` or `@transient` |
|
|
113
|
+
|
|
114
|
+
- **Default values**: `0` (Int, Float), `''` (String, ID), `false` (Boolean), the first value of a non-null enum,
|
|
115
|
+
`null` otherwise.
|
|
116
|
+
- **Generated rules**: `required` for a `String!`, an `ID!` or a non-null custom scalar; `pattern` for
|
|
117
|
+
`@pattern`; `oneOf` for an enum (with `null` when it is nullable). The foreign keys are checked by ramdb2.
|
|
118
|
+
- **Deletion policy without `@onDelete`**: `CASCADE` for a required key, `SET_ZERO` for an optional one, as in the
|
|
119
|
+
v1. Without a list relation pointing back: `NOTHING`.
|
|
120
|
+
|
|
121
|
+
### Finders
|
|
122
|
+
|
|
123
|
+
Each index gets static finders that read it directly:
|
|
124
|
+
|
|
125
|
+
```js
|
|
126
|
+
Book.findByIdAuthor(3) // the inverse index of each foreign key
|
|
127
|
+
Author.findByCode('VH') // @index
|
|
128
|
+
Book.findByIdAuthorAndTitle(3, 'Germinal') // @index(fields: [...]): the last arguments can be left out
|
|
129
|
+
Book.findByYear(1885) // @index(type: BTREE)
|
|
130
|
+
Book.rangeOfYear({ gte: 1880 }, { reverse: true })
|
|
131
|
+
Book.search('germ') // @index(type: FULLTEXT): one full-text index per type
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
An index with a `name:` gets a finder named `findBy` + the name.
|
|
135
|
+
|
|
136
|
+
### Computed fields
|
|
137
|
+
|
|
138
|
+
ramdb2-cli inverts each dependency path and generates the code that invalidates the right values, in the methods
|
|
139
|
+
`_invalidateDependents` and `_invalidateLinks` of every type the path goes through. You only write the compute
|
|
140
|
+
function, in the extended class:
|
|
141
|
+
|
|
142
|
+
```js
|
|
143
|
+
// db/extended/author.js
|
|
144
|
+
export default class Author extends AuthorBase {
|
|
145
|
+
computeLoanCount() {
|
|
146
|
+
let count = 0
|
|
147
|
+
for (const book of this.books) count += book.loans.size
|
|
148
|
+
return count
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
Until it is written, reading the field throws `Author must implement computeLoanCount()`.
|
|
154
|
+
|
|
155
|
+
### Checks
|
|
156
|
+
|
|
157
|
+
Every problem of the schema is listed at once:
|
|
158
|
+
|
|
159
|
+
```
|
|
160
|
+
Invalid schema:
|
|
161
|
+
- Project.tasks: @field(name: "idProjet") needs an object relation projet: Project in Task
|
|
162
|
+
- Task.tags: a list of scalars cannot be persistent: add @transient or @computed
|
|
163
|
+
- Task.a: depends "project.nope": nope is not a field of Project
|
|
164
|
+
- Task: computed fields depend on each other in a cycle: a -> b -> c -> a
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
A type used but not defined in the files given (defined by another layer) is read as a scalar, with a warning.
|
|
168
|
+
|
|
169
|
+
---
|
|
170
|
+
|
|
171
|
+
## new
|
|
172
|
+
|
|
173
|
+
```sh
|
|
174
|
+
ramdb2-cli new my_project
|
|
175
|
+
cd my_project
|
|
176
|
+
npm install
|
|
177
|
+
npm start # http://localhost:4000
|
|
178
|
+
npm run dev # the same, with readable logs (pino-pretty)
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
The folder must be empty or missing. ramdb2-cli writes the project, then runs `generate`:
|
|
182
|
+
|
|
183
|
+
| File | Content |
|
|
184
|
+
|---|---|
|
|
185
|
+
| `package.json` | `ramdb2-core`, `ramdb2-server` (and `ramdb2-cli` in dev), at the version of this ramdb2-cli; scripts `start`, `dev`, `generate`, `test`, `backup`, `create-user`; `pino-pretty` in dev |
|
|
186
|
+
| `.env.example` | the variables read at the start, with the command that makes a `TOKEN_SECRET` |
|
|
187
|
+
| `schema/preTypeDefs.graphql` | an example model: projects and tasks, an enum, full-text, a computed field; and the users (unique login, `@private` password) |
|
|
188
|
+
| `schema/project.graphql` | the operations written by hand: `health`, `changePassword`, `setPassword` |
|
|
189
|
+
| `db/extended/project.js` | an example extended class, with a rule and a compute function |
|
|
190
|
+
| `src/config.js` | the options of `startServer`, shared by the server and the tests: `auth`, `checkEntry`, the `context` (IP, user agent) and the `logging` |
|
|
191
|
+
| `src/auth.js` | `verifyCredentials` and `findUser`, for the authentication module of ramdb2-server |
|
|
192
|
+
| `src/index.js` | the start: `PORT`, `DB_PATH`, `LOG_LEVEL`, `TRUST_PROXY`, `TOKEN_SECRET` and `TOKEN_DURATION` from the environment or `.env` |
|
|
193
|
+
| `src/permissions.js`, `src/resolvers.js` | the permissions and the resolvers of the project |
|
|
194
|
+
| `scripts/backup.js` | a hot backup, with an example of cron in the README |
|
|
195
|
+
| `scripts/createUser.js` | `npm run create-user -- <login> [ADMIN\|USER]`: asks the password, creates the user or changes its password. The server must be stopped |
|
|
196
|
+
| `test/server.test.js` | a test of the API on an SQLite database in memory |
|
|
197
|
+
|
|
198
|
+
**Authentication is wired, but open.** `newToken`, `renewToken` and `me` work as soon as `TOKEN_SECRET` is set
|
|
199
|
+
(the server refuses to start without it), but `checkEntry` and the permissions allow everything. To close the
|
|
200
|
+
API: create a first user with `npm run create-user -- <login>`, uncomment the line of `checkEntry` in
|
|
201
|
+
`src/config.js`, then write the permissions on `context.user`. The password is `@private`: it is set by
|
|
202
|
+
`create-user`, by `changePassword(password, newPassword)` for the logged-in user, or by `setPassword(id, password)`
|
|
203
|
+
for an `ADMIN`. These mutations block the server while hashing, about 150 ms per hash.
|
|
204
|
+
|
|
205
|
+
`--packages <folder>` depends on the `packages` folder of a clone of the ramdb2 repository instead, through `file:`
|
|
206
|
+
paths: to try a change of ramdb2 before it is published. The paths are relative for a project next to the
|
|
207
|
+
repository, absolute otherwise. npm copies these packages into the `node_modules` of the project: after a change in
|
|
208
|
+
the repository, run `npm install` again in the project.
|
|
209
|
+
|
|
210
|
+
### With a web site: `--with-client`
|
|
211
|
+
|
|
212
|
+
```sh
|
|
213
|
+
ramdb2-cli new my_site --with-client
|
|
214
|
+
cd my_site
|
|
215
|
+
npm install # once, at the root: installs server/ and web/
|
|
216
|
+
cp server/.env.example server/.env # then set TOKEN_SECRET
|
|
217
|
+
npm run create-user -- admin # a first user, server stopped
|
|
218
|
+
npm run server # http://localhost:4000
|
|
219
|
+
npm run web # in another terminal: http://localhost:5173
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
One project, two npm workspaces:
|
|
223
|
+
|
|
224
|
+
| Path | Content |
|
|
225
|
+
|---|---|
|
|
226
|
+
| `package.json` | the workspaces; scripts `generate` (server, then site), `server`, `web`, `build`, `test`, `create-user` |
|
|
227
|
+
| `server/` | the server project above |
|
|
228
|
+
| `web/package.json` | `ramdb2-client`, `ramdb2-vue` (and `ramdb2-cli` in dev), at the version of this ramdb2-cli, Vue, vue-router, Vite; scripts `dev`, `build`, `preview`, `generate` |
|
|
229
|
+
| `web/vite.config.js` | in development, `/graphql` goes to the server, on port 4000 |
|
|
230
|
+
| `web/src/main.js` | the connection to the server, the routes (home, login, error page), the menu |
|
|
231
|
+
| `web/src/App.vue`, `web/src/pages/Home.vue` | the structure of the site, and a home page |
|
|
232
|
+
| `web/src/db/` | the client classes, generated from the schema of `server/` ([`client`](#client)) |
|
|
233
|
+
|
|
234
|
+
A minimal skeleton: add the pages in `web/src/pages`, their routes and the menu in `web/src/main.js`. The README of
|
|
235
|
+
`web/` shows a page with a whole CRUD table. `npm run build` compiles the site into `web/dist/`; serving it in
|
|
236
|
+
production is up to you for now.
|
|
237
|
+
|
|
238
|
+
---
|
|
239
|
+
|
|
240
|
+
## client
|
|
241
|
+
|
|
242
|
+
```sh
|
|
243
|
+
ramdb2-cli client --schema ../my_server/schema/preTypeDefs.graphql --dest src/model
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
Run in the client application, on the preTypeDefs of its server (several `--schema` files are read as one schema,
|
|
247
|
+
as for `generate`). It writes, in `--dest`:
|
|
248
|
+
|
|
249
|
+
| File | Content | Rewritten |
|
|
250
|
+
|---|---|---|
|
|
251
|
+
| `generated/<table>.js` | `XxxBase extends ClientObject` (from `ramdb2-client`): `typeName`, `operations`, `fields`, `computed`, `transient`, `fullText`, `relations`, `defaults`, `generatedRules`, and a getter per field, foreign key, relation, computed and transient field | at each generation |
|
|
252
|
+
| `extended/<table>.js` | `Xxx extends XxxBase`: the code of the application (`static rules`, getters) | never (created when missing) |
|
|
253
|
+
| `index.js` | the extended classes, and `classes` for `configure({ classes })` | at each generation |
|
|
254
|
+
|
|
255
|
+
- **Read-only instances**: getters only (`this._f`, `this._c` for computed and transient fields, `this._relation('name')`), no setter. Never a `#`
|
|
256
|
+
private field: it breaks the reactive proxy of Vue.
|
|
257
|
+
- `fields`: `id`, the foreign keys (`idProject`), then the stored fields. `@private` fields are left out, as in the
|
|
258
|
+
API.
|
|
259
|
+
- `transient`: the `@transient` fields of a scalar type (scalar, enum, custom scalar, list of them), always loaded
|
|
260
|
+
with the object. One of an object type, or with a required argument, is left out with a warning.
|
|
261
|
+
- `fullText`: the fields of the `FULLTEXT` index, in the order of the schema (`[]` without one), for a search with `$text`.
|
|
262
|
+
- `generatedRules`: the same rules as the server (`required`, `pattern`, `oneOf`), plus `requiredKey('idProject')`
|
|
263
|
+
for a required object relation.
|
|
264
|
+
- `operations`: the names of the standard operations of ramdb2-server (`projects`, `projectById`, …).
|
|
265
|
+
|
|
266
|
+
---
|
|
267
|
+
|
|
268
|
+
## plantuml
|
|
269
|
+
|
|
270
|
+
```sh
|
|
271
|
+
ramdb2-cli plantuml --schema schema/preTypeDefs.graphql --output model.puml
|
|
272
|
+
plantuml -tsvg model.puml
|
|
273
|
+
```
|
|
274
|
+
|
|
275
|
+
The entity-relationship diagram of the persistent types:
|
|
276
|
+
|
|
277
|
+
- one package per `@group`; the types without group outside;
|
|
278
|
+
- for each table: the id, the foreign keys with their target (and `0 = none` when optional), the stored fields,
|
|
279
|
+
then the computed and transient fields in grey;
|
|
280
|
+
- for each foreign key, an association with its cardinality (`||` required, `|o` optional) and its deletion policy.
|
|
281
|
+
|
|
282
|
+
```
|
|
283
|
+
author ||--o{ book : idAuthor (CASCADE)
|
|
284
|
+
book |o--o{ book : idSequel (SET_ZERO)
|
|
285
|
+
book ||--o{ loan : idBook (RESTRICT)
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
Without `--output`, the diagram is printed. Render it with the PlantUML plugin of your IDE, or as SVG: in PNG,
|
|
289
|
+
PlantUML cuts the image at 4096 pixels.
|
|
290
|
+
|
|
291
|
+
---
|
|
292
|
+
|
|
293
|
+
## query
|
|
294
|
+
|
|
295
|
+
```sh
|
|
296
|
+
ramdb2-cli query prod '{ projects { total } }'
|
|
297
|
+
ramdb2-cli query prod 'query($q: TaskQuery) { tasks(query: $q) { total items { name } } }' \
|
|
298
|
+
--variables '{"q": {"where": {"$text": {"$search": "design"}}, "limit": 10}}'
|
|
299
|
+
ramdb2-cli query prod --file report.graphql --variables '{"year": 2026}'
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
Sends a GraphQL query to the server of a profile and prints the JSON response. The exit code is 1 when the
|
|
303
|
+
response holds errors: it can be used in scripts.
|
|
304
|
+
|
|
305
|
+
### Profiles
|
|
306
|
+
|
|
307
|
+
One file per server, `~/.config/ramdb2-cli/<profile>.json` (or `$XDG_CONFIG_HOME/ramdb2-cli`):
|
|
308
|
+
|
|
309
|
+
```json
|
|
310
|
+
{
|
|
311
|
+
"url": "https://api.example.com/graphql",
|
|
312
|
+
"login": "manu",
|
|
313
|
+
"auth": {
|
|
314
|
+
"query": "query($login: String!, $password: String!) { newToken(login: $login, password: $password) }",
|
|
315
|
+
"header": "authorization",
|
|
316
|
+
"prefix": "Bearer "
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
Without `auth`, the query is sent without token. `header` defaults to `authorization`, `prefix` to nothing.
|
|
322
|
+
This profile fits a server with the authentication module of ramdb2-server.
|
|
323
|
+
|
|
324
|
+
### Token and password
|
|
325
|
+
|
|
326
|
+
- The token is obtained with `auth.query`: it is the only value of its response.
|
|
327
|
+
- It is kept in `~/.cache/ramdb2-cli/<profile>.token` (or `$XDG_CACHE_HOME`), readable by you only, until it
|
|
328
|
+
expires. Its expiry is read in the token: the standard JWT `exp`, or `expiration` in milliseconds. A token
|
|
329
|
+
that expires within 30 seconds is renewed, and so is a token the server refuses (HTTP 401 or
|
|
330
|
+
`UNAUTHENTICATED`), once.
|
|
331
|
+
- **The password is never stored**: it comes from `RAMDB2_CLI_PASSWORD`, or is asked on the terminal, without echo.
|
|
332
|
+
|
|
333
|
+
Passing the query in variables is also the way to send the `$` keys of the query syntax: GraphQL does not
|
|
334
|
+
allow them in the text of a query.
|
|
335
|
+
|
|
336
|
+
---
|
|
337
|
+
|
|
338
|
+
## convert
|
|
339
|
+
|
|
340
|
+
```sh
|
|
341
|
+
ramdb2-cli convert --input preTypeDefs.v1.graphql --output preTypeDefs.graphql
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
Writes a copy of a v1 preTypeDefs with directives instead of annotations. The comments, the order and the rest
|
|
345
|
+
of the descriptions are kept. An existing output is replaced only with `--force`.
|
|
346
|
+
|
|
347
|
+
| v1 | v2 |
|
|
348
|
+
|---|---|
|
|
349
|
+
| `[PERSISTENT]` on a type | `@persistent` |
|
|
350
|
+
| `[GROUP=TASK]` | `@group(name: "TASK")` |
|
|
351
|
+
| `[PERSISTENT]` on a field | nothing: persistent by default |
|
|
352
|
+
| a field without `[PERSISTENT]` | `@transient` |
|
|
353
|
+
| `[FIELD=idTask]` | `@field(name: "idTask")` |
|
|
354
|
+
|
|
355
|
+
The deletion policies of the v1 lived in JavaScript (`extIndexConfig`): they are not converted. A warning lists
|
|
356
|
+
each list relation to check; write an `@onDelete` where the policy is not the default one.
|
|
357
|
+
|
|
358
|
+
---
|
|
359
|
+
|
|
360
|
+
## Programmatic use
|
|
361
|
+
|
|
362
|
+
```js
|
|
363
|
+
import { generate, generateClient, newProject, plantuml, query, convert, readSchema } from 'ramdb2-cli'
|
|
364
|
+
|
|
365
|
+
const { written, kept, warnings } = generate({ schema: 'schema/preTypeDefs.graphql', dest: '.' })
|
|
366
|
+
generateClient({ schema: '../my_server/schema/preTypeDefs.graphql', dest: 'src/model' }) // same result
|
|
367
|
+
const model = readSchema(source) // throws a SchemaError listing every problem
|
|
368
|
+
const puml = plantuml('schema/preTypeDefs.graphql')
|
|
369
|
+
const { status, body } = await query({ profile: 'prod', query: '{ projects { total } }' })
|
|
370
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ramdb2-cli",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "2.0.0-alpha.0",
|
|
4
|
+
"description": "Code generator and project scaffolding for ramdb2 and ramdb2-server",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": "./src/index.js",
|
|
7
|
+
"bin": {
|
|
8
|
+
"ramdb2-cli": "./src/cli.js"
|
|
9
|
+
},
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"author": "Emmanuel Leparquier",
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "git+https://gitlab.com/eleparquier/ramdb2.git",
|
|
15
|
+
"directory": "packages/ramdb2-cli"
|
|
16
|
+
},
|
|
17
|
+
"homepage": "https://gitlab.com/eleparquier/ramdb2/-/tree/master/packages/ramdb2-cli",
|
|
18
|
+
"files": [
|
|
19
|
+
"src",
|
|
20
|
+
"CHANGELOG.md"
|
|
21
|
+
],
|
|
22
|
+
"scripts": {
|
|
23
|
+
"test": "node --test \"test/**/*.test.js\""
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"graphql": "^16.14.2"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"ramdb2-core": "^2.0.0-alpha.0",
|
|
30
|
+
"@vitejs/plugin-vue": "^6.0.10",
|
|
31
|
+
"vite": "^8.3.5",
|
|
32
|
+
"vue": "^3.5.44",
|
|
33
|
+
"vue-router": "^5.4.0"
|
|
34
|
+
}
|
|
35
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { parseArgs } from 'node:util'
|
|
4
|
+
import { generate, generateClient } from './generate.js'
|
|
5
|
+
import { convert } from './convert.js'
|
|
6
|
+
import { newProject } from './new.js'
|
|
7
|
+
import { plantuml } from './plantuml.js'
|
|
8
|
+
import { query } from './query.js'
|
|
9
|
+
|
|
10
|
+
const HELP = `ramdb2-cli: code generator of ramdb2
|
|
11
|
+
|
|
12
|
+
ramdb2-cli generate --schema <preTypeDefs.graphql> [--schema <other.graphql>...] --dest <folder>
|
|
13
|
+
Generates the classes (db/generated, rewritten; db/extended, created once), db/index.js,
|
|
14
|
+
schema/typeDefs.graphql and schema/operations.graphql. Several --schema files are read as one schema.
|
|
15
|
+
|
|
16
|
+
ramdb2-cli client --schema <preTypeDefs.graphql> [--schema <other.graphql>...] --dest <folder>
|
|
17
|
+
Generates the classes of a ramdb2-client application from the schema of its server: generated/ (rewritten),
|
|
18
|
+
extended/ (created once) and index.js, with the classes for configure({ classes }).
|
|
19
|
+
|
|
20
|
+
ramdb2-cli plantuml --schema <preTypeDefs.graphql> [--schema <other.graphql>...] [--output <model.puml>]
|
|
21
|
+
Entity-relationship diagram of the persistent types, in PlantUML: one package per @group,
|
|
22
|
+
foreign keys with their deletion policy. Printed, or written to --output.
|
|
23
|
+
Render it with an IDE plugin, or "plantuml -tsvg model.puml" (a PNG is cut at 4096 pixels).
|
|
24
|
+
|
|
25
|
+
ramdb2-cli query <profile> '<graphql>' [--variables '<json>'] | --file <query.graphql>
|
|
26
|
+
Sends a GraphQL query to the server of the profile (~/.config/ramdb2-cli/<profile>.json), with a token
|
|
27
|
+
renewed when it expires and kept in ~/.cache/ramdb2-cli. The password comes from RAMDB2_CLI_PASSWORD,
|
|
28
|
+
or is asked. Profile: { "url": ..., "login": ..., "auth": { "query": "query($login: String!,
|
|
29
|
+
$password: String!) { newToken(login: $login, password: $password) }" } }
|
|
30
|
+
|
|
31
|
+
ramdb2-cli new <folder> [--with-client] [--packages <folder>]
|
|
32
|
+
Creates a project on ramdb2 and ramdb2-server, ready to start: npm install, then npm start.
|
|
33
|
+
--with-client: one project with two npm workspaces, the server in server/ and a web site in web/
|
|
34
|
+
(ramdb2-client, ramdb2-vue), its classes generated from the schema of the server.
|
|
35
|
+
--packages: the packages folder of a ramdb2 repository, to depend on it through file: paths
|
|
36
|
+
(default: the packages from npm, at the version of this ramdb2-cli).
|
|
37
|
+
|
|
38
|
+
ramdb2-cli convert --input <v1 preTypeDefs> --output <v2 preTypeDefs> [--force]
|
|
39
|
+
Converts the v1 annotations ([PERSISTENT], [GROUP=], [FIELD=]) into directives, in a new file.
|
|
40
|
+
`
|
|
41
|
+
|
|
42
|
+
const commands = {
|
|
43
|
+
new(values, [dir]) {
|
|
44
|
+
if (dir === undefined) return usage('new needs the folder of the project')
|
|
45
|
+
const withClient = values['with-client'] ?? false
|
|
46
|
+
const { files } = newProject({ dir, packages: values.packages, withClient })
|
|
47
|
+
for (const path of files) console.log(`written ${path}`)
|
|
48
|
+
console.log(withClient
|
|
49
|
+
? `\nNext: cd ${dir} && npm install, set TOKEN_SECRET in server/.env, then npm run server and npm run web (see README.md)`
|
|
50
|
+
: `\nNext: cd ${dir} && npm install && npm start`)
|
|
51
|
+
},
|
|
52
|
+
async query(values, [profile, text]) {
|
|
53
|
+
const source = values.file === undefined ? text : readFileSync(values.file, 'utf8')
|
|
54
|
+
if (profile === undefined || source === undefined) return usage('query needs a profile and a query (or --file)')
|
|
55
|
+
const variables = values.variables === undefined ? undefined : JSON.parse(values.variables)
|
|
56
|
+
const { status, body } = await query({ profile, query: source, variables })
|
|
57
|
+
console.log(typeof body === 'string' ? body : JSON.stringify(body, null, 2))
|
|
58
|
+
if (status >= 400 || body?.errors !== undefined) process.exitCode = 1
|
|
59
|
+
},
|
|
60
|
+
plantuml(values) {
|
|
61
|
+
if (values.schema === undefined) return usage('plantuml needs --schema')
|
|
62
|
+
const source = plantuml(values.schema)
|
|
63
|
+
if (values.output === undefined) process.stdout.write(source)
|
|
64
|
+
else {
|
|
65
|
+
writeFileSync(values.output, source)
|
|
66
|
+
console.log(`written ${values.output}`)
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
generate(values) {
|
|
70
|
+
if (values.schema === undefined || values.dest === undefined) return usage('generate needs --schema and --dest')
|
|
71
|
+
report(generate({ schema: values.schema, dest: values.dest }))
|
|
72
|
+
},
|
|
73
|
+
client(values) {
|
|
74
|
+
if (values.schema === undefined || values.dest === undefined) return usage('client needs --schema and --dest')
|
|
75
|
+
report(generateClient({ schema: values.schema, dest: values.dest }))
|
|
76
|
+
},
|
|
77
|
+
convert(values) {
|
|
78
|
+
if (values.input === undefined || values.output === undefined) return usage('convert needs --input and --output')
|
|
79
|
+
if (existsSync(values.output) && !values.force) return usage(`${values.output} exists: add --force to replace it`)
|
|
80
|
+
const result = convert(readFileSync(values.input, 'utf8'))
|
|
81
|
+
writeFileSync(values.output, result.source)
|
|
82
|
+
console.log(`${result.types} persistent types converted into ${values.output}`)
|
|
83
|
+
for (const warning of result.warnings) console.log(`warning ${warning}`)
|
|
84
|
+
},
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function report({ written, kept, warnings }) {
|
|
88
|
+
for (const path of written) console.log(`written ${path}`)
|
|
89
|
+
for (const path of kept) console.log(`kept ${path} (written by hand)`)
|
|
90
|
+
for (const warning of warnings) console.log(`warning ${warning}`)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function usage(message) {
|
|
94
|
+
console.error(`${message}\n\n${HELP}`)
|
|
95
|
+
process.exitCode = 1
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const { values, positionals } = parseArgs({
|
|
99
|
+
allowPositionals: true,
|
|
100
|
+
options: {
|
|
101
|
+
schema: { type: 'string', multiple: true },
|
|
102
|
+
dest: { type: 'string' },
|
|
103
|
+
input: { type: 'string' },
|
|
104
|
+
output: { type: 'string' },
|
|
105
|
+
force: { type: 'boolean' },
|
|
106
|
+
packages: { type: 'string' },
|
|
107
|
+
'with-client': { type: 'boolean' },
|
|
108
|
+
variables: { type: 'string' },
|
|
109
|
+
file: { type: 'string' },
|
|
110
|
+
help: { type: 'boolean', short: 'h' },
|
|
111
|
+
},
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
const command = commands[positionals[0]]
|
|
115
|
+
if (values.help || command === undefined) {
|
|
116
|
+
console.log(HELP)
|
|
117
|
+
} else {
|
|
118
|
+
try {
|
|
119
|
+
await command(values, positionals.slice(1))
|
|
120
|
+
} catch (error) {
|
|
121
|
+
console.error(error.name === 'SchemaError' || error.message.startsWith('No profile') ? error.message : error)
|
|
122
|
+
process.exitCode = 1
|
|
123
|
+
}
|
|
124
|
+
}
|
package/src/convert.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { Kind, parse } from 'graphql'
|
|
2
|
+
|
|
3
|
+
// Converts a v1 preTypeDefs (annotations in the descriptions) into a v2 one (directives), D17.
|
|
4
|
+
// The text is edited in place: comments, order and formatting are kept.
|
|
5
|
+
// type: [PERSISTENT] -> @persistent, [GROUP=X] -> @group(name: "X")
|
|
6
|
+
// field of a persistent type: [PERSISTENT] -> nothing (persistent by default), [FIELD=x] -> @field(name: "x"),
|
|
7
|
+
// no [PERSISTENT] -> @transient
|
|
8
|
+
// The deletion policies of extIndexConfig are JavaScript: they are not converted (see the warnings).
|
|
9
|
+
|
|
10
|
+
const PERSISTENT = /^\s*\[PERSISTENT\]\s*$/
|
|
11
|
+
const GROUP = /^\s*\[GROUP=([A-Za-z0-9_]+)\]\s*$/
|
|
12
|
+
const FIELD = /^\s*\[FIELD=([A-Za-z0-9_]+)\]\s*$/
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* @param {string} source v1 preTypeDefs
|
|
16
|
+
* @returns {{source: string, types: number, warnings: string[]}}
|
|
17
|
+
*/
|
|
18
|
+
export function convert(source) {
|
|
19
|
+
const document = parse(source)
|
|
20
|
+
const edits = []
|
|
21
|
+
const warnings = []
|
|
22
|
+
let types = 0
|
|
23
|
+
|
|
24
|
+
for (const definition of document.definitions) {
|
|
25
|
+
if (definition.kind !== Kind.OBJECT_TYPE_DEFINITION) continue
|
|
26
|
+
const typeAnnotations = annotations(definition.description)
|
|
27
|
+
if (!typeAnnotations.persistent) continue
|
|
28
|
+
types++
|
|
29
|
+
const directives = [' @persistent']
|
|
30
|
+
if (typeAnnotations.group !== undefined) directives.push(` @group(name: "${typeAnnotations.group}")`)
|
|
31
|
+
edits.push({ start: definition.name.loc.end, end: definition.name.loc.end, text: directives.join('') })
|
|
32
|
+
// The location of a definition starts at its description: the keyword comes after it
|
|
33
|
+
const keyword = source.indexOf('type', definition.description.loc.end)
|
|
34
|
+
cleanDescription(source, definition.description, keyword, typeAnnotations.rest, edits)
|
|
35
|
+
|
|
36
|
+
for (const field of definition.fields ?? []) {
|
|
37
|
+
const fieldAnnotations = annotations(field.description)
|
|
38
|
+
const added = []
|
|
39
|
+
if (!fieldAnnotations.persistent) added.push(' @transient')
|
|
40
|
+
if (fieldAnnotations.field !== undefined) added.push(` @field(name: "${fieldAnnotations.field}")`)
|
|
41
|
+
if (fieldAnnotations.persistent && fieldAnnotations.field !== undefined) {
|
|
42
|
+
warnings.push(`${definition.name.value}.${field.name.value}: check its deletion policy in extIndexConfig, ` +
|
|
43
|
+
'and write it with @onDelete(action:) if it is not the default (CASCADE for a required key, SET_ZERO otherwise)')
|
|
44
|
+
}
|
|
45
|
+
if (added.length > 0) edits.push({ start: field.type.loc.end, end: field.type.loc.end, text: added.join('') })
|
|
46
|
+
if (field.description !== undefined) {
|
|
47
|
+
cleanDescription(source, field.description, field.name.loc.start, fieldAnnotations.rest, edits)
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
let result = source
|
|
53
|
+
for (const edit of edits.sort((a, b) => b.start - a.start)) {
|
|
54
|
+
result = result.slice(0, edit.start) + edit.text + result.slice(edit.end)
|
|
55
|
+
}
|
|
56
|
+
return { source: result, types, warnings }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function annotations(description) {
|
|
60
|
+
const found = { persistent: false, group: undefined, field: undefined, rest: [] }
|
|
61
|
+
if (description === undefined) return found
|
|
62
|
+
for (const line of description.value.split('\n')) {
|
|
63
|
+
let match
|
|
64
|
+
if (PERSISTENT.test(line)) found.persistent = true
|
|
65
|
+
else if ((match = GROUP.exec(line)) !== null) found.group = match[1]
|
|
66
|
+
else if ((match = FIELD.exec(line)) !== null) found.field = match[1]
|
|
67
|
+
else found.rest.push(line)
|
|
68
|
+
}
|
|
69
|
+
while (found.rest.length > 0 && found.rest[0].trim() === '') found.rest.shift()
|
|
70
|
+
while (found.rest.length > 0 && found.rest.at(-1).trim() === '') found.rest.pop()
|
|
71
|
+
return found
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Rewrites a description without its annotations, or removes it when nothing else is left
|
|
75
|
+
function cleanDescription(source, description, nextStart, rest, edits) {
|
|
76
|
+
if (description === undefined) return
|
|
77
|
+
const { start, end } = description.loc
|
|
78
|
+
if (rest.length === 0) {
|
|
79
|
+
// Up to the next token: the indentation of the line before the description stays in place
|
|
80
|
+
const lineStart = source.lastIndexOf('\n', start) + 1
|
|
81
|
+
const indent = source.slice(lineStart, start)
|
|
82
|
+
edits.push({ start: lineStart, end: nextStart, text: indent })
|
|
83
|
+
return
|
|
84
|
+
}
|
|
85
|
+
const indent = source.slice(source.lastIndexOf('\n', start) + 1, start)
|
|
86
|
+
const text = rest.length === 1 && !rest[0].includes('"')
|
|
87
|
+
? `"${rest[0].trim()}"`
|
|
88
|
+
: ['"""', ...rest.map(line => indent + line.trim()), indent + '"""'].join('\n')
|
|
89
|
+
edits.push({ start, end, text })
|
|
90
|
+
}
|