This repository has been archived by the owner on Jul 27, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.ts
349 lines (291 loc) · 8.79 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import * as fs from 'fs'
import * as inquirer from 'inquirer'
import yaml from 'js-yaml'
import * as path from 'path'
import pluralize from 'pluralize'
import { findPrismaConfigFile, importYogaConfig } from '../../../config'
import { prettify, resolvePrettierOptions } from '../../../helpers'
import { Config } from '../../../types'
import { spawnAsync } from '../../spawnAsync'
import execa = require('execa')
export default async (argv: Record<string, string>) => {
const { yogaConfig, projectDir } = importYogaConfig({ env: argv.env })
const hasDb = !!yogaConfig.prisma
const inputTypeQuestion: inquirer.Question<{ inputTypeName: string }> = {
name: 'inputTypeName',
message: 'Input the name of your type',
type: 'input',
validate(input: string) {
if (!input || input.length === 0) {
return 'Type name should be at least one character'
}
if (!/^[_a-zA-Z][_a-zA-Z0-9]*$/.test(input)) {
return `Type name must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ but "${input}" does not`
}
return true
},
}
let { inputTypeName } = await inquirer.prompt(inputTypeQuestion)
const typeName = upperFirst(inputTypeName)
if (hasDb) {
let crudOperations: string[] | null = null
const { datamodelPath, datamodelContent } = getPrismaDatamodel(projectDir)
const relativeDatamodelPath = path.relative(projectDir, datamodelPath)
while (isModelNameAlreadyDefined(inputTypeName, datamodelContent)) {
const { inputTypeName: retry } = await inquirer.prompt([
{
...inputTypeQuestion,
message:
'Type name already defined in your datamodel. Please try another one:',
},
])
inputTypeName = retry
}
const { exposeCrudOps } = await inquirer.prompt<{ exposeCrudOps: boolean }>(
[
{
name: 'exposeCrudOps',
message: 'Do you want to expose CRUD operations ?',
type: 'confirm',
},
],
)
if (exposeCrudOps) {
const { operations } = await inquirer.prompt<{ operations: string[] }>([
{
name: 'operations',
message: 'Select the operations you would like to expose',
type: 'checkbox',
choices: [
new inquirer.Separator('Queries'),
`Query.${typeName.toLowerCase()}`,
`Query.${pluralize(typeName.toLowerCase())}`,
new inquirer.Separator('Mutations'),
`Mutation.create${typeName}`,
`Mutation.delete${typeName}`,
`Mutation.update${typeName}`,
],
},
])
crudOperations = operations
}
updateDatamodel(datamodelPath, typeName)
console.log(`
We have added a type '${inputTypeName}' in your \`${relativeDatamodelPath}\` file !
Before we continue, please do the following steps:
1. Go to your \`${relativeDatamodelPath}\` file
2. Add the desired fields to your model
3. Confirm with Y once you're done, we'll run \`prisma deploy\` for you
`)
const { allStepsDone } = await inquirer.prompt<{ allStepsDone: boolean }>([
{
name: 'allStepsDone',
message: 'Did you go through all the steps ?',
type: 'confirm',
},
])
if (allStepsDone) {
await runPrismaDeploy()
const filePath = await scaffoldType(
yogaConfig,
typeName,
hasDb,
crudOperations,
)
const relativePath = path.relative(projectDir, filePath)
console.log(`
Scaffolding of ${relativePath} succesfuly done !
A few more optional steps:
1. Go to ${relativePath}
2. Expose/customize your persisted model using \`t.prismaFields([...])\`
`)
} else {
console.log('Exiting now.')
}
process.exit(0)
}
const filePath = await scaffoldType(yogaConfig, typeName, hasDb, null)
const relativePath = path.relative(projectDir, filePath)
console.log(`\
Scaffolded new file at ${relativePath}
Next steps:
- Go to ./src/graphql/${typeName}.ts
- Expose your persisted fields
`)
}
async function scaffoldType(
config: Config,
typeName: string,
hasDb: boolean,
crudOperations: string[] | null,
): Promise<string> {
const typePath = path.join(config.resolversPath, `${typeName}.ts`)
if (fs.existsSync(typePath)) {
throw new Error(`Cannot override existing file at ${typePath}.`)
}
const content = hasDb
? scaffoldTypeWithDb(typeName, crudOperations)
: scaffoldTypeWithoutDb(typeName)
const prettierOptions = await resolvePrettierOptions(process.cwd())
try {
fs.writeFileSync(typePath, prettify(content, prettierOptions))
} catch (e) {
console.error(e)
}
return typePath
}
function scaffoldTypeWithDb(
typeName: string,
crudOperations: string[] | null,
): string {
let content = `\
import { prismaObjectType${
crudOperations && crudOperations.length > 0 ? ', prismaExtendType' : ''
} } from 'yoga'
export const ${typeName} = prismaObjectType({
name: '${typeName}',
definition(t) {
// All fields exposed thanks the to wildcard operator
// Expose, hide or customize specific fields with t.prismaFields(['id', 'otherField', ...])
t.prismaFields(['*'])
}
})
`
if (crudOperations && crudOperations.length > 0) {
const queryOperations = crudOperations
.filter(op => op.startsWith('Query'))
.map(op => `'${op.replace('Query.', '')}'`)
const mutationOperations = crudOperations
.filter(op => op.startsWith('Mutation'))
.map(op => `'${op.replace('Mutation.', '')}'`)
if (queryOperations.length > 0) {
content += `
export const ${typeName}Query = prismaExtendType({
type: 'Query',
definition(t) {
t.prismaFields([${queryOperations.join(', ')}])
}
})
`
}
if (mutationOperations.length > 0) {
content += `
export const ${typeName}Mutation = prismaExtendType({
type: 'Mutation',
definition(t) {
t.prismaFields([${mutationOperations.join(', ')}])
}
})
`
}
}
return content
}
function scaffoldTypeWithoutDb(typeName: string) {
return `\
import { objectType } from 'yoga'
export const ${typeName} = objectType({
name: '${typeName}',
definition(t) {
// Expose your fields using t.field()/string()/boolean().. here
}
})
`
}
function getPrismaDatamodel(
projectDir: string,
): { datamodelPath: string; datamodelContent: string } {
const configPath = findPrismaConfigFile(projectDir)
if (!configPath) {
throw new Error('Could not find `prisma.yml` file')
}
let definition: null | any = null
try {
const file = fs.readFileSync(configPath, 'utf-8')
definition = yaml.safeLoad(file)
} catch (e) {
throw new Error(`Yaml parsing error in ${configPath}: ${e.message}`)
}
if (!definition.datamodel) {
throw new Error('Missing `datamodel` property in prisma.yml file')
}
const unresolvedTypesPath = Array.isArray(definition.datamodel)
? definition.datamodel[0]
: definition.datamodel
const datamodelPath = path.join(path.dirname(configPath), unresolvedTypesPath)
return {
datamodelPath,
datamodelContent: fs.readFileSync(datamodelPath).toString(),
}
}
function updateDatamodel(datamodelPath: string, typeName: string): void {
const typeToAdd = `\n
type ${typeName} {
# Add your fields here
id: ID! @unique
}`
try {
fs.appendFileSync(datamodelPath, typeToAdd)
} catch (e) {
console.error(e)
}
}
/**
* Uppercase the first letter of a string. Useful when generating type names.
*/
function upperFirst(s: string): string {
return s.replace(/^\w/, c => c.toUpperCase())
}
function isModelNameAlreadyDefined(modelName: string, datamodelString: string) {
return datamodelString.includes(`type ${modelName}`)
}
async function runPrismaDeploy(): Promise<any> {
try {
if (isYarnInstalled()) {
if (isPrismaInstalledLocally()) {
return runCommand('yarn prisma deploy')
}
if (isPrismaInstalledGlobally()) {
return runCommand('prisma deploy')
}
} else {
if (isPrismaInstalledLocally()) {
return runCommand('npm run prisma deploy')
}
if (isPrismaInstalledGlobally()) {
await runCommand(`prisma deploy`)
}
}
} catch (e) {
console.error(e)
}
}
async function isPrismaInstalledGlobally(): Promise<boolean> {
try {
await execa.shell(`prisma --version`, { stdio: `ignore` })
return true
} catch (err) {
return false
}
}
async function isPrismaInstalledLocally(): Promise<boolean> {
try {
await execa.shell(`yarn prisma --version`, { stdio: `ignore` })
return true
} catch (err) {
return false
}
}
async function isYarnInstalled(): Promise<boolean> {
try {
await execa.shell(`yarnpkg --version`, { stdio: `ignore` })
return true
} catch (err) {
return false
}
}
async function runCommand(command: string) {
const [cmd, ...rest] = command.split(' ')
const childProcess = spawnAsync(cmd, rest, { stdio: 'inherit' })
return childProcess
}