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/src/new.js
ADDED
|
@@ -0,0 +1,619 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { basename, join, relative, resolve } from 'node:path'
|
|
3
|
+
import { generate, generateClient } from './generate.js'
|
|
4
|
+
|
|
5
|
+
// ramdb2-cli new <project> (spec section 12): a project ready to start, on ramdb2 and ramdb2-server.
|
|
6
|
+
// The packages are installed from npm, at the version of this ramdb2-cli: all of them share one version (D53).
|
|
7
|
+
// With packages (the packages folder of a ramdb2 monorepo), from that folder with file: dependencies instead.
|
|
8
|
+
|
|
9
|
+
const VERSION = JSON.parse(readFileSync(join(import.meta.dirname, '../package.json'), 'utf8')).version
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Creates a project in an empty or missing folder, then generates its classes and schema.
|
|
13
|
+
* Without withClient: the server at the root of the folder. With withClient (D52): one project, two npm workspaces,
|
|
14
|
+
* server/ (the same server) and web/ (a site on ramdb2-client and ramdb2-vue, its classes generated from the schema
|
|
15
|
+
* of server/).
|
|
16
|
+
* @param {{dir: string, packages?: string, withClient?: boolean}} options packages: the folder holding the packages
|
|
17
|
+
* of ramdb2, to depend on them through file: paths (default: the npm packages, at the version of this ramdb2-cli)
|
|
18
|
+
* @returns {{files: string[]}} paths relative to dir
|
|
19
|
+
*/
|
|
20
|
+
export function newProject({ dir, packages, withClient = false }) {
|
|
21
|
+
if (existsSync(dir) && readdirSync(dir).length > 0) throw new Error(`${dir} is not empty`)
|
|
22
|
+
const name = basename(resolve(dir))
|
|
23
|
+
if (!withClient) return { files: writeServer(dir, name, packages) }
|
|
24
|
+
const files = [
|
|
25
|
+
...writeFiles(dir, { 'package.json': ROOT_PACKAGE(name), '.gitignore': 'node_modules/\n', 'README.md': ROOT_README(name) }),
|
|
26
|
+
...writeServer(join(dir, 'server'), `${name}-server`, packages).map(path => `server/${path}`),
|
|
27
|
+
...writeWeb(join(dir, 'web'), name, packages).map(path => `web/${path}`),
|
|
28
|
+
]
|
|
29
|
+
return { files }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// The version range of a package (D53): ^ and the version of this ramdb2-cli; with packages, its file: path,
|
|
33
|
+
// relative for a project next to the monorepo (../ramdb2/packages/ramdb2-core), absolute when far from it
|
|
34
|
+
function linker(dir, packages) {
|
|
35
|
+
if (packages === undefined) return () => `^${VERSION}`
|
|
36
|
+
return pkg => {
|
|
37
|
+
const path = relative(resolve(dir), join(packages, pkg))
|
|
38
|
+
return 'file:' + (path.split('/').filter(part => part === '..').length > 3 ? join(packages, pkg) : path)
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function writeFiles(dir, files) {
|
|
43
|
+
for (const [path, content] of Object.entries(files)) {
|
|
44
|
+
mkdirSync(join(dir, path, '..'), { recursive: true })
|
|
45
|
+
writeFileSync(join(dir, path), content)
|
|
46
|
+
}
|
|
47
|
+
return Object.keys(files)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function writeServer(dir, name, packages) {
|
|
51
|
+
const link = linker(dir, packages)
|
|
52
|
+
const files = {
|
|
53
|
+
'package.json': JSON.stringify({
|
|
54
|
+
name,
|
|
55
|
+
version: '0.1.0',
|
|
56
|
+
private: true,
|
|
57
|
+
type: 'module',
|
|
58
|
+
engines: { node: '>=22.9' },
|
|
59
|
+
scripts: {
|
|
60
|
+
start: 'node --env-file-if-exists=.env src/index.js',
|
|
61
|
+
// The logs are JSON lines (spec section 14): pino-pretty makes them readable, in development only
|
|
62
|
+
dev: 'node --env-file-if-exists=.env src/index.js | pino-pretty',
|
|
63
|
+
generate: 'ramdb2-cli generate --schema schema/preTypeDefs.graphql --dest .',
|
|
64
|
+
test: 'node --test "test/**/*.test.js"',
|
|
65
|
+
backup: 'node --env-file-if-exists=.env scripts/backup.js',
|
|
66
|
+
'create-user': 'node --env-file-if-exists=.env scripts/createUser.js',
|
|
67
|
+
},
|
|
68
|
+
dependencies: { 'ramdb2-core': link('ramdb2-core'), 'ramdb2-server': link('ramdb2-server'), 'graphql': '^16.14.2' },
|
|
69
|
+
devDependencies: { 'ramdb2-cli': link('ramdb2-cli'), 'pino-pretty': '^13.2.0' },
|
|
70
|
+
}, null, 2) + '\n',
|
|
71
|
+
'.gitignore': 'node_modules/\ndata/\nbackups/\n.env\n',
|
|
72
|
+
'.env.example': 'PORT=4000\nDB_PATH=./data/dev.db\nLOG_LEVEL=info\n'
|
|
73
|
+
+ '# Signing key of the tokens, at least 32 bytes: node -e "console.log(crypto.randomBytes(48).toString(\'base64url\'))"\n'
|
|
74
|
+
+ 'TOKEN_SECRET=\n# Lifetime of a token, in seconds\nTOKEN_DURATION=7200\n'
|
|
75
|
+
+ '# Behind a reverse proxy (Docker, Traefik, nginx): the client IP is read in X-Forwarded-For\n# TRUST_PROXY=1\n# In production: Apollo hides the stack traces from the clients and closes the introspection\n# NODE_ENV=production\n',
|
|
76
|
+
'README.md': README(name),
|
|
77
|
+
'schema/preTypeDefs.graphql': SCHEMA,
|
|
78
|
+
'schema/project.graphql': PROJECT_SCHEMA,
|
|
79
|
+
'db/extended/project.js': EXTENDED_PROJECT,
|
|
80
|
+
'src/config.js': CONFIG,
|
|
81
|
+
'src/auth.js': AUTH,
|
|
82
|
+
'src/index.js': INDEX,
|
|
83
|
+
'src/permissions.js': PERMISSIONS,
|
|
84
|
+
'src/resolvers.js': RESOLVERS,
|
|
85
|
+
'scripts/backup.js': BACKUP,
|
|
86
|
+
'scripts/createUser.js': CREATE_USER,
|
|
87
|
+
'test/server.test.js': TEST,
|
|
88
|
+
}
|
|
89
|
+
writeFiles(dir, files)
|
|
90
|
+
mkdirSync(join(dir, 'data'), { recursive: true })
|
|
91
|
+
const generated = generate({ schema: join(dir, 'schema/preTypeDefs.graphql'), dest: dir })
|
|
92
|
+
return [...Object.keys(files), ...generated.written]
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const README = name => `# ${name}
|
|
96
|
+
|
|
97
|
+
GraphQL server on [ramdb2](https://www.npmjs.com/package/ramdb2-core): the data lives in memory, as objects, and is
|
|
98
|
+
persisted in SQLite.
|
|
99
|
+
|
|
100
|
+
\`\`\`sh
|
|
101
|
+
npm install
|
|
102
|
+
npm run generate # after each change of schema/preTypeDefs.graphql
|
|
103
|
+
npm start # http://localhost:4000
|
|
104
|
+
npm run dev # the same, with readable logs (pino-pretty)
|
|
105
|
+
npm test
|
|
106
|
+
\`\`\`
|
|
107
|
+
|
|
108
|
+
| Folder | Content |
|
|
109
|
+
|---|---|
|
|
110
|
+
| \`schema/preTypeDefs.graphql\` | the data model, with the directives of ramdb2-cli |
|
|
111
|
+
| \`schema/project.graphql\` | the operations written by hand (\`extend type Query\`) |
|
|
112
|
+
| \`db/generated/\`, \`schema/typeDefs.graphql\`, \`schema/operations.graphql\` | generated: do not edit |
|
|
113
|
+
| \`db/extended/\` | business rules and computed fields, written by hand |
|
|
114
|
+
| \`src/\` | server configuration, permissions, resolvers of the project |
|
|
115
|
+
|
|
116
|
+
Logs: one JSON line per request and per event, on stdout. \`LOG_LEVEL\` sets the level (\`debug\`, \`info\`,
|
|
117
|
+
\`warn\`, \`error\`, \`silent\`). The fields of the log lines and the alerts are set in \`src/config.js\` (\`logging\`).
|
|
118
|
+
A field marked \`@sensitive\` in the schema, or an argument in \`schema/project.graphql\`, is masked in the logs.
|
|
119
|
+
|
|
120
|
+
Authentication: \`newToken(login, password)\` gives a token, sent as \`Authorization: Bearer <token>\`;
|
|
121
|
+
\`renewToken\` renews it, \`me\` gives the current user. Set \`TOKEN_SECRET\` in \`.env\` (see \`.env.example\`), then
|
|
122
|
+
create a first user with \`npm run create-user -- <login>\`. Everything is open at first: uncomment the line of
|
|
123
|
+
\`checkEntry\` in \`src/config.js\` to require a logged-in user, and write the permissions in \`src/permissions.js\`.
|
|
124
|
+
|
|
125
|
+
Backup, while the server runs: \`npm run backup\`. Every night with cron:
|
|
126
|
+
|
|
127
|
+
\`\`\`
|
|
128
|
+
0 3 * * * cd /path/to/${name} && npm run backup
|
|
129
|
+
\`\`\`
|
|
130
|
+
`
|
|
131
|
+
|
|
132
|
+
const SCHEMA = `# The data model: each @persistent type is a ramdb2 table. Run "npm run generate" after a change.
|
|
133
|
+
|
|
134
|
+
enum ProjectStatus { DRAFT OPEN CLOSED }
|
|
135
|
+
|
|
136
|
+
"A project and its tasks."
|
|
137
|
+
type Project @persistent {
|
|
138
|
+
id: Int!
|
|
139
|
+
name: String! @index(type: FULLTEXT)
|
|
140
|
+
status: ProjectStatus!
|
|
141
|
+
tasks: [Task!] @field(name: "idProject")
|
|
142
|
+
"Hours of all the tasks of the project."
|
|
143
|
+
totalHours: Float! @computed(depends: ["tasks.hours"])
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
type Task @persistent {
|
|
147
|
+
id: Int!
|
|
148
|
+
project: Project!
|
|
149
|
+
name: String!
|
|
150
|
+
hours: Float!
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
enum UserRole { USER ADMIN }
|
|
154
|
+
|
|
155
|
+
"A user who logs in with newToken. Created by npm run create-user."
|
|
156
|
+
type User @persistent {
|
|
157
|
+
id: Int!
|
|
158
|
+
login: String! @index(unique: true)
|
|
159
|
+
"scrypt hash (hashPassword of ramdb2-server): @private, never in the API"
|
|
160
|
+
password: String @private
|
|
161
|
+
role: UserRole!
|
|
162
|
+
}
|
|
163
|
+
`
|
|
164
|
+
|
|
165
|
+
const PROJECT_SCHEMA = `# Operations written by hand: their resolvers are in src/resolvers.js
|
|
166
|
+
|
|
167
|
+
extend type Query {
|
|
168
|
+
"State of the database: open, number of objects per table."
|
|
169
|
+
health: JSON!
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
extend type Mutation {
|
|
173
|
+
"Changes the password of the logged-in user. Blocks the server about 300 ms (two scrypt hashes)."
|
|
174
|
+
changePassword(password: String! @sensitive, newPassword: String! @sensitive): Boolean!
|
|
175
|
+
"Sets the password of a user, for an ADMIN. Blocks the server about 150 ms."
|
|
176
|
+
setPassword(id: Int!, password: String! @sensitive): Boolean!
|
|
177
|
+
}
|
|
178
|
+
`
|
|
179
|
+
|
|
180
|
+
const EXTENDED_PROJECT = `import ProjectBase from '../generated/project.js'
|
|
181
|
+
|
|
182
|
+
/** Written by hand: business rules, computed fields and methods. Created once by ramdb2-cli, never rewritten. */
|
|
183
|
+
export default class Project extends ProjectBase {
|
|
184
|
+
|
|
185
|
+
// Validation rules per field, run at commit after the generated ones: (values, obj) => "" | message
|
|
186
|
+
static rules = {
|
|
187
|
+
name: [values => values.name.length > 100 ? 'name is too long' : ''],
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// Integrity rules checked by delete(): (values, obj) => "" | message
|
|
191
|
+
static deleteRules = []
|
|
192
|
+
|
|
193
|
+
/** @returns {number} depends on tasks.hours */
|
|
194
|
+
computeTotalHours() {
|
|
195
|
+
let total = 0
|
|
196
|
+
for (const task of this.tasks) total += task.hours
|
|
197
|
+
return total
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
`
|
|
201
|
+
|
|
202
|
+
const CONFIG = `import { join } from 'node:path'
|
|
203
|
+
import { GraphQLError } from 'graphql'
|
|
204
|
+
import { loadTypeDefs } from 'ramdb2-server'
|
|
205
|
+
import { classes } from '../db/index.js'
|
|
206
|
+
import permissions from './permissions.js'
|
|
207
|
+
import resolvers from './resolvers.js'
|
|
208
|
+
import { findUser, verifyCredentials } from './auth.js'
|
|
209
|
+
|
|
210
|
+
const root = join(import.meta.dirname, '..')
|
|
211
|
+
|
|
212
|
+
// The client IP. Behind a reverse proxy (TRUST_PROXY=1), it is the last address of X-Forwarded-For, the one added
|
|
213
|
+
// by the proxy: the first ones are written by the client and can be forged.
|
|
214
|
+
const clientIp = req => {
|
|
215
|
+
const forwarded = process.env.TRUST_PROXY ? req.headers['x-forwarded-for'] : undefined
|
|
216
|
+
return forwarded ? forwarded.split(',').at(-1).trim() : req.socket.remoteAddress
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Options of startServer, shared by src/index.js and the tests. */
|
|
220
|
+
export default {
|
|
221
|
+
classes,
|
|
222
|
+
typeDefs: loadTypeDefs(...['typeDefs', 'operations', 'project'].map(name => join(root, 'schema', name + '.graphql'))),
|
|
223
|
+
permissions,
|
|
224
|
+
resolvers,
|
|
225
|
+
// Authentication (D46 of ramdb2): newToken, renewToken and me; context.user is the user of the token, or null
|
|
226
|
+
auth: {
|
|
227
|
+
secret: process.env.TOKEN_SECRET,
|
|
228
|
+
duration: Number(process.env.TOKEN_DURATION ?? 7200),
|
|
229
|
+
verifyCredentials,
|
|
230
|
+
findUser,
|
|
231
|
+
userType: 'User',
|
|
232
|
+
},
|
|
233
|
+
// Called before each operation, except newToken, renewToken and me: throw to refuse it
|
|
234
|
+
checkEntry: (field, context) => {
|
|
235
|
+
// Uncomment to require a logged-in user
|
|
236
|
+
// if (!context.user) throw new GraphQLError('Log in first', { extensions: { code: 'UNAUTHENTICATED' } })
|
|
237
|
+
},
|
|
238
|
+
// The context of each request, given to the permissions and the resolvers; user is added to it
|
|
239
|
+
context: async ({ req }) => ({ ip: clientIp(req), userAgent: req.headers['user-agent'] }),
|
|
240
|
+
// The logs (spec section 14 of ramdb2): fields of the context written in each request line, alerts, variables
|
|
241
|
+
logging: {
|
|
242
|
+
context: context => ({ user: context.user?.id, ip: context.ip, userAgent: context.userAgent }),
|
|
243
|
+
slowUs: 100_000,
|
|
244
|
+
exclude: ['IntrospectionQuery'],
|
|
245
|
+
},
|
|
246
|
+
}
|
|
247
|
+
`
|
|
248
|
+
|
|
249
|
+
const INDEX = `import { startServer } from 'ramdb2-server'
|
|
250
|
+
import config from './config.js'
|
|
251
|
+
|
|
252
|
+
// Logs its URL once ready (line "server listening")
|
|
253
|
+
await startServer({
|
|
254
|
+
...config,
|
|
255
|
+
db: { path: process.env.DB_PATH ?? './data/dev.db' },
|
|
256
|
+
port: Number(process.env.PORT ?? 4000),
|
|
257
|
+
})
|
|
258
|
+
`
|
|
259
|
+
|
|
260
|
+
const PERMISSIONS = `// What a user may do with the objects of each type (D15). A missing entry allows.
|
|
261
|
+
// see filters the lists; create is checked on the new object; update receives the fields given.
|
|
262
|
+
export default {
|
|
263
|
+
default: {
|
|
264
|
+
see: (obj, context) => true,
|
|
265
|
+
create: (obj, context) => true,
|
|
266
|
+
update: (obj, context, fields) => true,
|
|
267
|
+
delete: (obj, context) => true,
|
|
268
|
+
},
|
|
269
|
+
// Project: { delete: (project, context) => project.status === 'DRAFT' },
|
|
270
|
+
// context.user is the logged-in user (null without a valid token): see src/auth.js
|
|
271
|
+
// User: { see: (user, context) => context.user?.role === 'ADMIN' || user === context.user },
|
|
272
|
+
}
|
|
273
|
+
`
|
|
274
|
+
|
|
275
|
+
const RESOLVERS = `import { GraphQLError } from 'graphql'
|
|
276
|
+
import { store } from 'ramdb2-core'
|
|
277
|
+
import { health, hashPasswordSync, verifyPasswordSync } from 'ramdb2-server'
|
|
278
|
+
|
|
279
|
+
const error = (message, code, extensions = {}) => new GraphQLError(message, { extensions: { code, ...extensions } })
|
|
280
|
+
|
|
281
|
+
// A mutation is synchronous (it runs in a transaction): the passwords are hashed with the Sync functions,
|
|
282
|
+
// which block the server about 150 ms each. Acceptable for a rare operation.
|
|
283
|
+
const checkNewPassword = (password, field) => {
|
|
284
|
+
if (password.length < 8) throw error('The password is too short', 'BAD_USER_INPUT', { errors: { [field]: 'at least 8 characters' } })
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// Resolvers of the project, merged over the standard ones (same name: replaced). Each mutation runs in a
|
|
288
|
+
// transaction opened by the server, and must be synchronous. \`standard\` holds the standard resolvers.
|
|
289
|
+
export default standard => ({
|
|
290
|
+
Query: {
|
|
291
|
+
health: () => health(),
|
|
292
|
+
},
|
|
293
|
+
Mutation: {
|
|
294
|
+
changePassword: (_, { password, newPassword }, context) => {
|
|
295
|
+
if (!context.user) throw error('Log in first', 'UNAUTHENTICATED')
|
|
296
|
+
if (!verifyPasswordSync(password, context.user.password)) {
|
|
297
|
+
throw error('Wrong password', 'BAD_USER_INPUT', { errors: { password: 'wrong password' } })
|
|
298
|
+
}
|
|
299
|
+
checkNewPassword(newPassword, 'newPassword')
|
|
300
|
+
context.user.password = hashPasswordSync(newPassword)
|
|
301
|
+
return true
|
|
302
|
+
},
|
|
303
|
+
setPassword: (_, { id, password }, context) => {
|
|
304
|
+
if (context.user?.role !== 'ADMIN') throw error('Only an ADMIN sets the password of a user', 'FORBIDDEN')
|
|
305
|
+
const user = store.get('user', id)
|
|
306
|
+
if (user === undefined) throw error(\`User #\${id} does not exist\`, 'NOT_FOUND')
|
|
307
|
+
checkNewPassword(password, 'password')
|
|
308
|
+
user.password = hashPasswordSync(password)
|
|
309
|
+
return true
|
|
310
|
+
},
|
|
311
|
+
},
|
|
312
|
+
})
|
|
313
|
+
`
|
|
314
|
+
|
|
315
|
+
const AUTH = `import { store } from 'ramdb2-core'
|
|
316
|
+
import { hashPassword, verifyPassword } from 'ramdb2-server'
|
|
317
|
+
import User from '../db/extended/user.js'
|
|
318
|
+
|
|
319
|
+
// Checked when the login is unknown, so that the answer takes as long as for a wrong password
|
|
320
|
+
const UNKNOWN = await hashPassword('')
|
|
321
|
+
|
|
322
|
+
/** The user of this login and password, or null (option auth.verifyCredentials). */
|
|
323
|
+
export async function verifyCredentials(login, password) {
|
|
324
|
+
const user = User.findByLogin(login).values().next().value
|
|
325
|
+
const ok = await verifyPassword(password, user?.password ?? UNKNOWN)
|
|
326
|
+
return ok && user !== undefined ? user : null
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** The user of an id, at each request (option auth.findUser). */
|
|
330
|
+
export function findUser(id) {
|
|
331
|
+
return store.get('user', id) ?? null
|
|
332
|
+
}
|
|
333
|
+
`
|
|
334
|
+
|
|
335
|
+
const CREATE_USER = `// npm run create-user -- <login> [ADMIN|USER]: asks the password, creates the user or changes its password
|
|
336
|
+
import { createInterface } from 'node:readline/promises'
|
|
337
|
+
import { SqliteStorage, store } from 'ramdb2-core'
|
|
338
|
+
import { hashPassword } from 'ramdb2-server'
|
|
339
|
+
import { classes, User } from '../db/index.js'
|
|
340
|
+
|
|
341
|
+
const [login, role = 'ADMIN'] = process.argv.slice(2)
|
|
342
|
+
if (!login) {
|
|
343
|
+
console.error('Usage: npm run create-user -- <login> [ADMIN|USER]')
|
|
344
|
+
process.exit(1)
|
|
345
|
+
}
|
|
346
|
+
const terminal = createInterface({ input: process.stdin, output: process.stdout })
|
|
347
|
+
const password = process.env.CREATE_USER_PASSWORD ?? await terminal.question('Password: ')
|
|
348
|
+
terminal.close()
|
|
349
|
+
const hash = await hashPassword(password)
|
|
350
|
+
|
|
351
|
+
// The server must be stopped: two processes do not write the same database
|
|
352
|
+
store.register(...classes)
|
|
353
|
+
store.open(new SqliteStorage(process.env.DB_PATH ?? './data/dev.db'))
|
|
354
|
+
const existing = User.findByLogin(login).values().next().value
|
|
355
|
+
store.transaction(() => {
|
|
356
|
+
if (existing) {
|
|
357
|
+
existing.password = hash
|
|
358
|
+
} else {
|
|
359
|
+
const user = new User()
|
|
360
|
+
Object.assign(user, { login, password: hash, role })
|
|
361
|
+
user.insert()
|
|
362
|
+
}
|
|
363
|
+
})
|
|
364
|
+
store.close()
|
|
365
|
+
console.log(existing ? \`Password of \${login} changed\` : \`User \${login} created\`)
|
|
366
|
+
`
|
|
367
|
+
|
|
368
|
+
const BACKUP = `// Hot backup of the database, safe while the server runs (SQLite backup API, WAL)
|
|
369
|
+
import { mkdirSync } from 'node:fs'
|
|
370
|
+
import { SqliteStorage } from 'ramdb2-core'
|
|
371
|
+
|
|
372
|
+
const source = process.env.DB_PATH ?? './data/dev.db'
|
|
373
|
+
const destination = \`./backups/\${new Date().toISOString().replace(/[:.]/g, '-')}.db\`
|
|
374
|
+
mkdirSync('./backups', { recursive: true })
|
|
375
|
+
const storage = new SqliteStorage(source)
|
|
376
|
+
await storage.backup(destination)
|
|
377
|
+
storage.close()
|
|
378
|
+
console.log(\`Backup written to \${destination}\`)
|
|
379
|
+
`
|
|
380
|
+
|
|
381
|
+
const TEST = `import { describe, it } from 'node:test'
|
|
382
|
+
import assert from 'node:assert/strict'
|
|
383
|
+
import { createContext, createServer, hashPassword } from 'ramdb2-server'
|
|
384
|
+
import { SqliteStorage, store } from 'ramdb2-core'
|
|
385
|
+
import config from '../src/config.js'
|
|
386
|
+
import { User } from '../db/index.js'
|
|
387
|
+
|
|
388
|
+
const options = {
|
|
389
|
+
...config,
|
|
390
|
+
auth: { ...config.auth, secret: 'a-secret-for-the-tests-of-at-least-32-bytes' },
|
|
391
|
+
db: { storage: new SqliteStorage(':memory:') },
|
|
392
|
+
logging: { ...config.logging, level: 'silent' },
|
|
393
|
+
}
|
|
394
|
+
const server = createServer(options)
|
|
395
|
+
|
|
396
|
+
// Runs an operation as a client sending this token
|
|
397
|
+
async function run(query, variables, token) {
|
|
398
|
+
const req = { headers: token === undefined ? {} : { authorization: \`Bearer \${token}\` }, socket: { remoteAddress: '127.0.0.1' } }
|
|
399
|
+
const response = await server.executeOperation({ query, variables }, { contextValue: await createContext(options)({ req }) })
|
|
400
|
+
return JSON.parse(JSON.stringify(response.body.singleResult))
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
describe('server', () => {
|
|
404
|
+
it('creates a project and computes its hours', async () => {
|
|
405
|
+
const created = await run('mutation { projectCreate(project: { name: "Alpha" }) { id } }')
|
|
406
|
+
const id = created.data.projectCreate.id
|
|
407
|
+
await run('mutation($id: Int!) { taskCreate(task: { idProject: $id, name: "design", hours: 3 }) { id } }', { id })
|
|
408
|
+
const result = await run('query($id: Int!) { projectById(id: $id) { name totalHours tasks { name } } }', { id })
|
|
409
|
+
assert.deepEqual(result.data.projectById, { name: 'Alpha', totalHours: 3, tasks: [{ name: 'design' }] })
|
|
410
|
+
})
|
|
411
|
+
|
|
412
|
+
it('logs a user in, who changes their password', async () => {
|
|
413
|
+
const hash = await hashPassword('secret12')
|
|
414
|
+
store.transaction(() => Object.assign(new User(), { login: 'admin', password: hash, role: 'ADMIN' }).insert())
|
|
415
|
+
const login = await run('query { newToken(login: "admin", password: "secret12") }')
|
|
416
|
+
const token = login.data.newToken
|
|
417
|
+
assert.deepEqual((await run('query { me { login role } }', {}, token)).data.me, { login: 'admin', role: 'ADMIN' })
|
|
418
|
+
const changed = await run('mutation { changePassword(password: "secret12", newPassword: "another1") }', {}, token)
|
|
419
|
+
assert.equal(changed.data.changePassword, true)
|
|
420
|
+
const again = await run('query { newToken(login: "admin", password: "another1") }')
|
|
421
|
+
assert.equal(typeof again.data.newToken, 'string')
|
|
422
|
+
})
|
|
423
|
+
})
|
|
424
|
+
`
|
|
425
|
+
|
|
426
|
+
// ---- With --with-client (D52): the root of the project, and the site in web/ ----
|
|
427
|
+
|
|
428
|
+
const ROOT_PACKAGE = name => JSON.stringify({
|
|
429
|
+
name,
|
|
430
|
+
private: true,
|
|
431
|
+
workspaces: ['server', 'web'],
|
|
432
|
+
scripts: {
|
|
433
|
+
// The schema of server/ makes the classes of both sides
|
|
434
|
+
generate: 'npm run generate -w server && npm run generate -w web',
|
|
435
|
+
server: 'npm run dev -w server',
|
|
436
|
+
web: 'npm run dev -w web',
|
|
437
|
+
build: 'npm run build -w web',
|
|
438
|
+
test: 'npm test --workspaces --if-present',
|
|
439
|
+
'create-user': 'npm run create-user -w server --',
|
|
440
|
+
},
|
|
441
|
+
}, null, 2) + '\n'
|
|
442
|
+
|
|
443
|
+
const ROOT_README = name => `# ${name}
|
|
444
|
+
|
|
445
|
+
A site on [ramdb2](https://gitlab.com/eleparquier/ramdb2): the GraphQL server in \`server/\`, the web site in \`web/\`,
|
|
446
|
+
two npm workspaces installed together.
|
|
447
|
+
|
|
448
|
+
\`\`\`sh
|
|
449
|
+
npm install # once, at the root: installs server/ and web/
|
|
450
|
+
cp server/.env.example server/.env # then set TOKEN_SECRET in server/.env
|
|
451
|
+
npm run create-user -- admin # a first user, server stopped
|
|
452
|
+
npm run server # the server, http://localhost:4000
|
|
453
|
+
npm run web # the site, in another terminal: http://localhost:5173
|
|
454
|
+
\`\`\`
|
|
455
|
+
|
|
456
|
+
| Command | Effect |
|
|
457
|
+
|---|---|
|
|
458
|
+
| \`npm run generate\` | after each change of \`server/schema/preTypeDefs.graphql\`: the classes of the server, then of the site |
|
|
459
|
+
| \`npm test\` | the tests of both |
|
|
460
|
+
| \`npm run build\` | the site, compiled into \`web/dist/\` |
|
|
461
|
+
|
|
462
|
+
See \`server/README.md\` and \`web/README.md\`.
|
|
463
|
+
`
|
|
464
|
+
|
|
465
|
+
function writeWeb(dir, project, packages) {
|
|
466
|
+
const link = linker(dir, packages)
|
|
467
|
+
const name = `${project}-web`
|
|
468
|
+
const files = {
|
|
469
|
+
'package.json': JSON.stringify({
|
|
470
|
+
name,
|
|
471
|
+
version: '0.1.0',
|
|
472
|
+
private: true,
|
|
473
|
+
type: 'module',
|
|
474
|
+
scripts: {
|
|
475
|
+
dev: 'vite',
|
|
476
|
+
build: 'vite build',
|
|
477
|
+
preview: 'vite preview',
|
|
478
|
+
generate: 'ramdb2-cli client --schema ../server/schema/preTypeDefs.graphql --dest src/db',
|
|
479
|
+
},
|
|
480
|
+
dependencies: {
|
|
481
|
+
'ramdb2-client': link('ramdb2-client'),
|
|
482
|
+
'ramdb2-vue': link('ramdb2-vue'),
|
|
483
|
+
'vue': '^3.5.44',
|
|
484
|
+
'vue-router': '^5.4.0',
|
|
485
|
+
},
|
|
486
|
+
devDependencies: { 'ramdb2-cli': link('ramdb2-cli'), '@vitejs/plugin-vue': '^6.0.10', 'vite': '^8.3.5' },
|
|
487
|
+
}, null, 2) + '\n',
|
|
488
|
+
'.gitignore': 'node_modules/\ndist/\n',
|
|
489
|
+
'README.md': WEB_README(name),
|
|
490
|
+
'index.html': WEB_INDEX(project),
|
|
491
|
+
'vite.config.js': VITE_CONFIG,
|
|
492
|
+
'src/main.js': WEB_MAIN(project),
|
|
493
|
+
'src/App.vue': WEB_APP,
|
|
494
|
+
'src/pages/Home.vue': WEB_HOME,
|
|
495
|
+
}
|
|
496
|
+
writeFiles(dir, files)
|
|
497
|
+
const generated = generateClient({ schema: join(dir, '..', 'server', 'schema', 'preTypeDefs.graphql'), dest: join(dir, 'src', 'db') })
|
|
498
|
+
return [...Object.keys(files), ...generated.written.map(path => `src/db/${path}`)]
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
const WEB_README = name => `# ${name}
|
|
502
|
+
|
|
503
|
+
The web site, in Vue, on [ramdb2-client](https://gitlab.com/eleparquier/ramdb2/-/tree/master/packages/ramdb2-client)
|
|
504
|
+
and [ramdb2-vue](https://gitlab.com/eleparquier/ramdb2/-/tree/master/packages/ramdb2-vue).
|
|
505
|
+
|
|
506
|
+
\`\`\`sh
|
|
507
|
+
npm run dev # http://localhost:5173, the server of ../server must run (npm run dev there)
|
|
508
|
+
npm run generate # after each change of ../server/schema/preTypeDefs.graphql
|
|
509
|
+
npm run build # the site, compiled into dist/
|
|
510
|
+
\`\`\`
|
|
511
|
+
|
|
512
|
+
| Path | Content |
|
|
513
|
+
|---|---|
|
|
514
|
+
| \`src/main.js\` | the connection to the server, the routes and the menu |
|
|
515
|
+
| \`src/pages/\` | the pages: one component per page, declared in the routes and in the menu |
|
|
516
|
+
| \`src/db/generated/\`, \`src/db/index.js\` | the classes of the objects, generated from the schema of the server: do not edit |
|
|
517
|
+
| \`src/db/extended/\` | the code of the site for each class (labels, methods), written by hand |
|
|
518
|
+
| \`vite.config.js\` | in development, \`/graphql\` is sent to the server, on port 4000 |
|
|
519
|
+
|
|
520
|
+
Every page needs a logged-in user, but the login page: create one in the server (\`npm run create-user -- <login>\`).
|
|
521
|
+
|
|
522
|
+
A page for a type, for instance \`src/pages/Projects.vue\`, then a route \`{ path: '/projects', component: Projects,
|
|
523
|
+
meta: { title: 'Projets' } }\` and a menu entry \`{ label: 'Projets', icon: 'folder', to: '/projects' }\` in
|
|
524
|
+
\`src/main.js\`:
|
|
525
|
+
|
|
526
|
+
\`\`\`vue
|
|
527
|
+
<script setup>
|
|
528
|
+
import { RdbCrud } from 'ramdb2-vue'
|
|
529
|
+
import { Project } from '../db/index.js'
|
|
530
|
+
</script>
|
|
531
|
+
|
|
532
|
+
<template>
|
|
533
|
+
<RdbCrud :type="Project" title="Projets" />
|
|
534
|
+
</template>
|
|
535
|
+
\`\`\`
|
|
536
|
+
`
|
|
537
|
+
|
|
538
|
+
const WEB_INDEX = name => `<!doctype html>
|
|
539
|
+
<html lang="fr">
|
|
540
|
+
<head>
|
|
541
|
+
<meta charset="utf-8">
|
|
542
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
543
|
+
<title>${name}</title>
|
|
544
|
+
</head>
|
|
545
|
+
<body>
|
|
546
|
+
<div id="app"></div>
|
|
547
|
+
<script type="module" src="/src/main.js"></script>
|
|
548
|
+
</body>
|
|
549
|
+
</html>
|
|
550
|
+
`
|
|
551
|
+
|
|
552
|
+
const VITE_CONFIG = `import { defineConfig } from 'vite'
|
|
553
|
+
import vue from '@vitejs/plugin-vue'
|
|
554
|
+
|
|
555
|
+
// In development, the GraphQL requests go to the server of ../server (npm run dev there), on its PORT
|
|
556
|
+
const proxy = { '/graphql': { target: 'http://localhost:4000', rewrite: () => '/' } }
|
|
557
|
+
|
|
558
|
+
export default defineConfig({
|
|
559
|
+
plugins: [vue()],
|
|
560
|
+
server: { proxy },
|
|
561
|
+
preview: { proxy },
|
|
562
|
+
})
|
|
563
|
+
`
|
|
564
|
+
|
|
565
|
+
const WEB_MAIN = name => `import { createApp } from 'vue'
|
|
566
|
+
import { createRouter, createWebHistory } from 'vue-router'
|
|
567
|
+
import { configure } from 'ramdb2-client'
|
|
568
|
+
import { createRamdb2Vue, requireLogin, RdbErrorPage, RdbLoginPage } from 'ramdb2-vue'
|
|
569
|
+
import { classes } from './db/index.js'
|
|
570
|
+
import App from './App.vue'
|
|
571
|
+
import Home from './pages/Home.vue'
|
|
572
|
+
|
|
573
|
+
// The server, through the proxy of Vite in development (vite.config.js)
|
|
574
|
+
configure({ url: '/graphql', classes })
|
|
575
|
+
|
|
576
|
+
const router = createRouter({
|
|
577
|
+
history: createWebHistory(),
|
|
578
|
+
routes: [
|
|
579
|
+
{ path: '/', component: Home, meta: { title: 'Accueil' } },
|
|
580
|
+
// Outside the structure of the site (bare): the login page, and the page of an unknown address
|
|
581
|
+
{ path: '/login', component: RdbLoginPage, meta: { title: 'Connexion', bare: true, public: true } },
|
|
582
|
+
{ path: '/:pathMatch(.*)*', component: RdbErrorPage, meta: { title: 'Page introuvable' } },
|
|
583
|
+
],
|
|
584
|
+
})
|
|
585
|
+
|
|
586
|
+
// Every page needs a logged-in user, but the login page
|
|
587
|
+
requireLogin(router)
|
|
588
|
+
|
|
589
|
+
// One entry per page: { label, icon, to }, or { label, icon, children: [...] } for a group
|
|
590
|
+
const menu = [
|
|
591
|
+
{ label: 'Accueil', icon: 'home', to: '/' },
|
|
592
|
+
]
|
|
593
|
+
|
|
594
|
+
createApp(App)
|
|
595
|
+
.use(router)
|
|
596
|
+
.use(createRamdb2Vue({ title: ${JSON.stringify(name)}, menu, locale: 'fr', loginPath: '/login' }))
|
|
597
|
+
.mount('#app')
|
|
598
|
+
`
|
|
599
|
+
|
|
600
|
+
const WEB_APP = `<script setup>
|
|
601
|
+
import { RdbApp } from 'ramdb2-vue'
|
|
602
|
+
</script>
|
|
603
|
+
|
|
604
|
+
<template>
|
|
605
|
+
<!-- The structure of the site: menu, top bar, the user of the session; the page of the route inside -->
|
|
606
|
+
<RdbApp />
|
|
607
|
+
</template>
|
|
608
|
+
`
|
|
609
|
+
|
|
610
|
+
const WEB_HOME = `<script setup>
|
|
611
|
+
import { RdbPage } from 'ramdb2-vue'
|
|
612
|
+
</script>
|
|
613
|
+
|
|
614
|
+
<template>
|
|
615
|
+
<RdbPage title="Accueil">
|
|
616
|
+
<p>Le site est prêt : ajoutez vos pages dans src/pages, leurs routes et le menu dans src/main.js.</p>
|
|
617
|
+
</RdbPage>
|
|
618
|
+
</template>
|
|
619
|
+
`
|