@frozencrow/create-api 0.1.1 → 0.1.4
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 +16 -8
- package/bin/create-api.js +84 -17
- package/lib/generate-service.js +203 -0
- package/package.json +11 -1
- package/template/README.md +11 -11
- package/template/package.json +1 -1
- package/template/src/app.ts +4 -5
- package/template/src/services/index.ts +9 -0
- package/template/test/auth.test.ts +49 -0
- package/template/test/{client.test.ts → widgets.test.ts} +17 -22
package/README.md
CHANGED
|
@@ -11,11 +11,23 @@ npm create @frozencrow/api my-app
|
|
|
11
11
|
npx @frozencrow/create-api my-app
|
|
12
12
|
```
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
It asks which services you want to create, then scaffolds them. You can also
|
|
15
|
+
pass them up front (and skip the prompt):
|
|
15
16
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
17
|
+
```bash
|
|
18
|
+
npm create @frozencrow/api my-app -- --services posts,comments,work-orders
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Each name becomes a multitenant service (schema + class + registration, wired
|
|
22
|
+
into `src/services/index.ts`). Leave it blank for no services. For fields and
|
|
23
|
+
other access models, use the `frozencrow` CLI afterwards:
|
|
24
|
+
`npx frozencrow generate service <name> --fields "..."`.
|
|
25
|
+
|
|
26
|
+
The scaffolder also:
|
|
27
|
+
|
|
28
|
+
- sets the project's package name and database name,
|
|
29
|
+
- writes a strong secret to `config/local.json` (git-ignored — uses the Feathers
|
|
30
|
+
config module, no `.env`).
|
|
19
31
|
|
|
20
32
|
Then:
|
|
21
33
|
|
|
@@ -25,10 +37,6 @@ npm install
|
|
|
25
37
|
npm run dev
|
|
26
38
|
```
|
|
27
39
|
|
|
28
|
-
The generated project depends on `@frozencrow/api-core` and includes an example
|
|
29
|
-
multitenant `widgets` service (`src/services/widgets/`) showing the pattern for
|
|
30
|
-
adding your own resources.
|
|
31
|
-
|
|
32
40
|
## License
|
|
33
41
|
|
|
34
42
|
MIT
|
package/bin/create-api.js
CHANGED
|
@@ -5,10 +5,11 @@
|
|
|
5
5
|
* Scaffolder for @frozencrow/api-core based projects.
|
|
6
6
|
*
|
|
7
7
|
* npm create @frozencrow/api my-app
|
|
8
|
-
* npx @frozencrow/create-api my-app
|
|
8
|
+
* npx @frozencrow/create-api my-app --services posts,comments
|
|
9
9
|
*
|
|
10
|
-
* Copies the bundled template, renames the project, generates a strong
|
|
11
|
-
*
|
|
10
|
+
* Copies the bundled template, renames the project, generates a strong secret
|
|
11
|
+
* into config/local.json, and scaffolds the services you name (replacing the
|
|
12
|
+
* bundled `widgets` example). Zero runtime dependencies.
|
|
12
13
|
*/
|
|
13
14
|
|
|
14
15
|
const fs = require('fs')
|
|
@@ -16,12 +17,31 @@ const path = require('path')
|
|
|
16
17
|
const crypto = require('crypto')
|
|
17
18
|
const readline = require('readline')
|
|
18
19
|
|
|
20
|
+
const { generateServiceFiles, writeServicesBarrel, isValidServiceName } = require('../lib/generate-service')
|
|
21
|
+
|
|
19
22
|
const TEMPLATE_DIR = path.join(__dirname, '..', 'template')
|
|
20
23
|
|
|
21
24
|
// Files that must be renamed on copy (npm strips/renames some dotfiles in
|
|
22
25
|
// published packages, so we ship them dot-less).
|
|
23
26
|
const RENAME_ON_COPY = { gitignore: '.gitignore' }
|
|
24
27
|
|
|
28
|
+
function parseArgs(argv) {
|
|
29
|
+
const out = { _: [], flags: {} }
|
|
30
|
+
for (let i = 0; i < argv.length; i++) {
|
|
31
|
+
const arg = argv[i]
|
|
32
|
+
if (arg.startsWith('--')) {
|
|
33
|
+
const body = arg.slice(2)
|
|
34
|
+
const eq = body.indexOf('=')
|
|
35
|
+
if (eq !== -1) out.flags[body.slice(0, eq)] = body.slice(eq + 1)
|
|
36
|
+
else if (i + 1 < argv.length && !argv[i + 1].startsWith('--')) out.flags[body] = argv[++i]
|
|
37
|
+
else out.flags[body] = true
|
|
38
|
+
} else {
|
|
39
|
+
out._.push(arg)
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return out
|
|
43
|
+
}
|
|
44
|
+
|
|
25
45
|
function isValidPackageName(name) {
|
|
26
46
|
return /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(name)
|
|
27
47
|
}
|
|
@@ -33,11 +53,8 @@ function copyDir(src, dest) {
|
|
|
33
53
|
const srcPath = path.join(src, entry.name)
|
|
34
54
|
const destName = RENAME_ON_COPY[entry.name] || entry.name
|
|
35
55
|
const destPath = path.join(dest, destName)
|
|
36
|
-
if (entry.isDirectory())
|
|
37
|
-
|
|
38
|
-
} else {
|
|
39
|
-
fs.copyFileSync(srcPath, destPath)
|
|
40
|
-
}
|
|
56
|
+
if (entry.isDirectory()) copyDir(srcPath, destPath)
|
|
57
|
+
else fs.copyFileSync(srcPath, destPath)
|
|
41
58
|
}
|
|
42
59
|
}
|
|
43
60
|
|
|
@@ -49,12 +66,46 @@ function ask(question) {
|
|
|
49
66
|
}))
|
|
50
67
|
}
|
|
51
68
|
|
|
69
|
+
// Parse a comma-separated services spec into validated, de-duped names.
|
|
70
|
+
function parseServices(spec) {
|
|
71
|
+
if (typeof spec !== 'string') return []
|
|
72
|
+
const seen = new Set()
|
|
73
|
+
const valid = []
|
|
74
|
+
for (const raw of spec.split(',').map((s) => s.trim()).filter(Boolean)) {
|
|
75
|
+
if (!isValidServiceName(raw)) {
|
|
76
|
+
console.warn(` skipping invalid service name "${raw}" (use letters, numbers, hyphens)`)
|
|
77
|
+
continue
|
|
78
|
+
}
|
|
79
|
+
const key = raw.toLowerCase()
|
|
80
|
+
if (seen.has(key)) continue
|
|
81
|
+
seen.add(key)
|
|
82
|
+
valid.push(raw)
|
|
83
|
+
}
|
|
84
|
+
return valid
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Replace the bundled `widgets` example with the user's services and rewrite the
|
|
88
|
+
// services barrel. Always removes the widgets example.
|
|
89
|
+
function applyServices(targetDir, serviceNames) {
|
|
90
|
+
const servicesDir = path.join(targetDir, 'src', 'services')
|
|
91
|
+
|
|
92
|
+
fs.rmSync(path.join(servicesDir, 'widgets'), { recursive: true, force: true })
|
|
93
|
+
fs.rmSync(path.join(targetDir, 'test', 'widgets.test.ts'), { force: true })
|
|
94
|
+
|
|
95
|
+
const tokens = serviceNames.map((name) => {
|
|
96
|
+
const n = generateServiceFiles(servicesDir, name)
|
|
97
|
+
console.log(` ${'create'} src/services/${n.dir}/`)
|
|
98
|
+
return n
|
|
99
|
+
})
|
|
100
|
+
writeServicesBarrel(servicesDir, tokens)
|
|
101
|
+
return tokens
|
|
102
|
+
}
|
|
103
|
+
|
|
52
104
|
async function main() {
|
|
53
|
-
|
|
105
|
+
const { _, flags } = parseArgs(process.argv.slice(2))
|
|
54
106
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
}
|
|
107
|
+
let projectName = _[0]
|
|
108
|
+
if (!projectName) projectName = await ask('Project name: ')
|
|
58
109
|
if (!projectName) {
|
|
59
110
|
console.error('Error: a project name is required.')
|
|
60
111
|
process.exit(1)
|
|
@@ -72,6 +123,16 @@ async function main() {
|
|
|
72
123
|
process.exit(1)
|
|
73
124
|
}
|
|
74
125
|
|
|
126
|
+
// Decide which services to scaffold: --services flag, else prompt (if
|
|
127
|
+
// interactive), else none.
|
|
128
|
+
let servicesSpec = flags.services
|
|
129
|
+
if (servicesSpec === undefined) {
|
|
130
|
+
servicesSpec = process.stdin.isTTY
|
|
131
|
+
? await ask('Services to create? Comma-separated names (e.g. posts,comments), or blank for none: ')
|
|
132
|
+
: ''
|
|
133
|
+
}
|
|
134
|
+
const serviceNames = parseServices(servicesSpec)
|
|
135
|
+
|
|
75
136
|
console.log(`\nCreating a new API in ${targetDir} ...`)
|
|
76
137
|
copyDir(TEMPLATE_DIR, targetDir)
|
|
77
138
|
|
|
@@ -95,12 +156,18 @@ async function main() {
|
|
|
95
156
|
// placeholder secret without committing it. In production, set AUTH_SECRET —
|
|
96
157
|
// it is mapped in config/custom-environment-variables.json.
|
|
97
158
|
const secret = crypto.randomBytes(48).toString('base64url')
|
|
98
|
-
const localConfig = { authentication: { secret } }
|
|
99
159
|
fs.writeFileSync(
|
|
100
160
|
path.join(targetDir, 'config', 'local.json'),
|
|
101
|
-
JSON.stringify(
|
|
161
|
+
JSON.stringify({ authentication: { secret } }, null, 4) + '\n'
|
|
102
162
|
)
|
|
103
163
|
|
|
164
|
+
// 4. Scaffold the requested services (replaces the bundled widgets example).
|
|
165
|
+
applyServices(targetDir, serviceNames)
|
|
166
|
+
|
|
167
|
+
const servicesLine = serviceNames.length
|
|
168
|
+
? `Scaffolded ${serviceNames.length} service${serviceNames.length === 1 ? '' : 's'}: ${serviceNames.join(', ')}.`
|
|
169
|
+
: 'No custom services yet — add one with `npx frozencrow generate service <name>`.'
|
|
170
|
+
|
|
104
171
|
console.log(`
|
|
105
172
|
Done! Next steps:
|
|
106
173
|
|
|
@@ -108,9 +175,9 @@ Done! Next steps:
|
|
|
108
175
|
npm install
|
|
109
176
|
npm run dev
|
|
110
177
|
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
178
|
+
${servicesLine}
|
|
179
|
+
A strong secret was written to config/local.json (git-ignored); configure the
|
|
180
|
+
rest in config/default.json.
|
|
114
181
|
`)
|
|
115
182
|
}
|
|
116
183
|
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
// Minimal, zero-dependency service generator used by the scaffolder. It emits
|
|
4
|
+
// the same three-file pattern as `frozencrow generate service <name>` for a
|
|
5
|
+
// multitenant (team-access) service with a single `name` field. For fields,
|
|
6
|
+
// access modes, and wiring, use the full `frozencrow generate service` CLI.
|
|
7
|
+
|
|
8
|
+
const fs = require('node:fs')
|
|
9
|
+
const path = require('node:path')
|
|
10
|
+
|
|
11
|
+
function words(input) {
|
|
12
|
+
return String(input)
|
|
13
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
|
14
|
+
.split(/[-_\s]+/)
|
|
15
|
+
.filter(Boolean)
|
|
16
|
+
.map((w) => w.toLowerCase())
|
|
17
|
+
}
|
|
18
|
+
const toKebab = (input) => words(input).join('-')
|
|
19
|
+
const toCamel = (input) =>
|
|
20
|
+
words(input)
|
|
21
|
+
.map((w, i) => (i === 0 ? w : w[0].toUpperCase() + w.slice(1)))
|
|
22
|
+
.join('')
|
|
23
|
+
const toPascal = (input) => {
|
|
24
|
+
const c = toCamel(input)
|
|
25
|
+
return c ? c[0].toUpperCase() + c.slice(1) : c
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// A valid service name: letters/numbers/hyphens, starting with a letter.
|
|
29
|
+
function isValidServiceName(name) {
|
|
30
|
+
return /^[a-z][a-z0-9-]*$/i.test(String(name))
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function schemaFile(n) {
|
|
34
|
+
return `import { resolve } from '@feathersjs/schema'
|
|
35
|
+
import { Type, getValidator, querySyntax, ObjectIdSchema } from '@feathersjs/typebox'
|
|
36
|
+
import type { Static } from '@feathersjs/typebox'
|
|
37
|
+
import { dataValidator, queryValidator } from '@frozencrow/api-core'
|
|
38
|
+
import type { HookContext } from '@frozencrow/api-core'
|
|
39
|
+
|
|
40
|
+
// A multitenant resource. \`organizationId\` scopes it to the caller's active
|
|
41
|
+
// organization — enforced automatically by teamAccessControl (via
|
|
42
|
+
// generateDefaultHooks in ${n.file}.ts).
|
|
43
|
+
export const ${n.camel}Schema = Type.Object(
|
|
44
|
+
{
|
|
45
|
+
_id: ObjectIdSchema(),
|
|
46
|
+
name: Type.String(),
|
|
47
|
+
organizationId: ObjectIdSchema(),
|
|
48
|
+
createdAt: Type.Number(),
|
|
49
|
+
updatedAt: Type.Number()
|
|
50
|
+
},
|
|
51
|
+
{ $id: '${n.Pascal}', additionalProperties: false }
|
|
52
|
+
)
|
|
53
|
+
export type ${n.Pascal} = Static<typeof ${n.camel}Schema>
|
|
54
|
+
export const ${n.camel}Resolver = resolve<${n.Pascal}, HookContext>({})
|
|
55
|
+
export const ${n.camel}ExternalResolver = resolve<${n.Pascal}, HookContext>({})
|
|
56
|
+
|
|
57
|
+
export const ${n.camel}DataSchema = Type.Intersect(
|
|
58
|
+
[
|
|
59
|
+
Type.Pick(${n.camel}Schema, ['name']),
|
|
60
|
+
Type.Object({
|
|
61
|
+
organizationId: Type.Optional(ObjectIdSchema()),
|
|
62
|
+
createdAt: Type.Optional(Type.Number()),
|
|
63
|
+
updatedAt: Type.Optional(Type.Number())
|
|
64
|
+
})
|
|
65
|
+
],
|
|
66
|
+
{ $id: '${n.Pascal}Data' }
|
|
67
|
+
)
|
|
68
|
+
export type ${n.Pascal}Data = Static<typeof ${n.camel}DataSchema>
|
|
69
|
+
export const ${n.camel}DataValidator = getValidator(${n.camel}DataSchema, dataValidator)
|
|
70
|
+
export const ${n.camel}DataResolver = resolve<${n.Pascal}, HookContext>({
|
|
71
|
+
organizationId: async (value, _data, context) =>
|
|
72
|
+
value || (context.params as any).user?.activeOrganization,
|
|
73
|
+
createdAt: async () => Date.now(),
|
|
74
|
+
updatedAt: async () => Date.now()
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
export const ${n.camel}PatchSchema = Type.Partial(
|
|
78
|
+
Type.Pick(${n.camel}Schema, ['name', 'organizationId', 'createdAt', 'updatedAt']),
|
|
79
|
+
{ $id: '${n.Pascal}Patch' }
|
|
80
|
+
)
|
|
81
|
+
export type ${n.Pascal}Patch = Static<typeof ${n.camel}PatchSchema>
|
|
82
|
+
export const ${n.camel}PatchValidator = getValidator(${n.camel}PatchSchema, dataValidator)
|
|
83
|
+
export const ${n.camel}PatchResolver = resolve<${n.Pascal}, HookContext>({
|
|
84
|
+
updatedAt: async () => Date.now()
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
export const ${n.camel}QueryProperties = Type.Pick(${n.camel}Schema, ['_id', 'name', 'organizationId', 'createdAt'])
|
|
88
|
+
export const ${n.camel}QuerySchema = Type.Intersect(
|
|
89
|
+
[querySyntax(${n.camel}QueryProperties), Type.Object({}, { additionalProperties: false })],
|
|
90
|
+
{ additionalProperties: false }
|
|
91
|
+
)
|
|
92
|
+
export type ${n.Pascal}Query = Static<typeof ${n.camel}QuerySchema>
|
|
93
|
+
export const ${n.camel}QueryValidator = getValidator(${n.camel}QuerySchema, queryValidator)
|
|
94
|
+
export const ${n.camel}QueryResolver = resolve<${n.Pascal}Query, HookContext>({})
|
|
95
|
+
`
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function classFile(n) {
|
|
99
|
+
return `import type { Params } from '@feathersjs/feathers'
|
|
100
|
+
import { MongoDBService } from '@feathersjs/mongodb'
|
|
101
|
+
import type { MongoDBAdapterParams, MongoDBAdapterOptions } from '@feathersjs/mongodb'
|
|
102
|
+
import type { Application } from '@frozencrow/api-core'
|
|
103
|
+
|
|
104
|
+
import type { ${n.Pascal}, ${n.Pascal}Data, ${n.Pascal}Patch, ${n.Pascal}Query } from './${n.file}.schema'
|
|
105
|
+
|
|
106
|
+
export interface ${n.Pascal}Params extends MongoDBAdapterParams<${n.Pascal}Query> {}
|
|
107
|
+
|
|
108
|
+
export class ${n.Pascal}Service<ServiceParams extends Params = ${n.Pascal}Params> extends MongoDBService<
|
|
109
|
+
${n.Pascal},
|
|
110
|
+
${n.Pascal}Data,
|
|
111
|
+
${n.Pascal}Params,
|
|
112
|
+
${n.Pascal}Patch
|
|
113
|
+
> {}
|
|
114
|
+
|
|
115
|
+
export const getOptions = (app: Application): MongoDBAdapterOptions => {
|
|
116
|
+
return {
|
|
117
|
+
paginate: app.get('paginate'),
|
|
118
|
+
Model: (app.get('mongodbClient') as Promise<any>).then((db) => db.collection('${n.path}'))
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
`
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function registrationFile(n) {
|
|
125
|
+
return `import { generateDefaultHooks } from '@frozencrow/api-core'
|
|
126
|
+
import type { Application } from '@frozencrow/api-core'
|
|
127
|
+
|
|
128
|
+
import { ${n.Pascal}Service, getOptions } from './${n.file}.class'
|
|
129
|
+
import {
|
|
130
|
+
${n.camel}DataValidator,
|
|
131
|
+
${n.camel}PatchValidator,
|
|
132
|
+
${n.camel}QueryValidator,
|
|
133
|
+
${n.camel}Resolver,
|
|
134
|
+
${n.camel}ExternalResolver,
|
|
135
|
+
${n.camel}DataResolver,
|
|
136
|
+
${n.camel}PatchResolver,
|
|
137
|
+
${n.camel}QueryResolver
|
|
138
|
+
} from './${n.file}.schema'
|
|
139
|
+
|
|
140
|
+
export const ${n.camel}Path = '${n.path}'
|
|
141
|
+
export const ${n.camel}Methods = ['find', 'get', 'create', 'patch', 'remove'] as const
|
|
142
|
+
|
|
143
|
+
// Full typing for app.use('${n.path}') / app.service('${n.path}').
|
|
144
|
+
declare module '@frozencrow/api-core/lib/declarations' {
|
|
145
|
+
interface ServiceTypes {
|
|
146
|
+
'${n.path}': ${n.Pascal}Service
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const schema = {
|
|
151
|
+
dataValidator: ${n.camel}DataValidator,
|
|
152
|
+
patchValidator: ${n.camel}PatchValidator,
|
|
153
|
+
queryValidator: ${n.camel}QueryValidator,
|
|
154
|
+
dataResolver: ${n.camel}DataResolver,
|
|
155
|
+
patchResolver: ${n.camel}PatchResolver,
|
|
156
|
+
queryResolver: ${n.camel}QueryResolver,
|
|
157
|
+
resultResolver: ${n.camel}Resolver,
|
|
158
|
+
externalResolver: ${n.camel}ExternalResolver
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export const ${n.camel} = (app: Application) => {
|
|
162
|
+
app.use(${n.camel}Path, new ${n.Pascal}Service(getOptions(app)), {
|
|
163
|
+
methods: [...${n.camel}Methods],
|
|
164
|
+
events: []
|
|
165
|
+
})
|
|
166
|
+
app.service(${n.camel}Path).hooks(generateDefaultHooks({ schema }))
|
|
167
|
+
}
|
|
168
|
+
`
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Returns { camel, Pascal, path, file, dir } naming tokens for a service name.
|
|
172
|
+
function names(rawName) {
|
|
173
|
+
const kebab = toKebab(rawName)
|
|
174
|
+
return { camel: toCamel(rawName), Pascal: toPascal(rawName), path: kebab, file: kebab, dir: kebab }
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Write the three service files under `servicesDir/<name>/`. Returns the tokens.
|
|
178
|
+
function generateServiceFiles(servicesDir, rawName) {
|
|
179
|
+
const n = names(rawName)
|
|
180
|
+
const outDir = path.join(servicesDir, n.dir)
|
|
181
|
+
fs.mkdirSync(outDir, { recursive: true })
|
|
182
|
+
fs.writeFileSync(path.join(outDir, `${n.file}.schema.ts`), schemaFile(n))
|
|
183
|
+
fs.writeFileSync(path.join(outDir, `${n.file}.class.ts`), classFile(n))
|
|
184
|
+
fs.writeFileSync(path.join(outDir, `${n.file}.ts`), registrationFile(n))
|
|
185
|
+
return n
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Write src/services/index.ts registering the given services (by their tokens).
|
|
189
|
+
function writeServicesBarrel(servicesDir, serviceNames) {
|
|
190
|
+
const imports = serviceNames
|
|
191
|
+
.map((n) => `import { ${n.camel} } from './${n.dir}/${n.file}'`)
|
|
192
|
+
.join('\n')
|
|
193
|
+
const configures = serviceNames.map((n) => ` app.configure(${n.camel})`).join('\n')
|
|
194
|
+
|
|
195
|
+
const body = serviceNames.length
|
|
196
|
+
? `${imports}\n\n// Register your services here. Generate new ones with:\n// npx frozencrow generate service <name>\nexport const services = (app: Application) => {\n${configures}\n}\n`
|
|
197
|
+
: `// Register your services here. Generate new ones with:\n// npx frozencrow generate service <name>\nexport const services = (_app: Application) => {}\n`
|
|
198
|
+
|
|
199
|
+
const content = `import type { Application } from '@frozencrow/api-core'\n\n${body}`
|
|
200
|
+
fs.writeFileSync(path.join(servicesDir, 'index.ts'), content)
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
module.exports = { generateServiceFiles, writeServicesBarrel, names, isValidServiceName }
|
package/package.json
CHANGED
|
@@ -1,9 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@frozencrow/create-api",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.4",
|
|
4
4
|
"description": "Scaffold a new API project powered by @frozencrow/api-core",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Eric Uldall",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/Frozen-Crow/api-boilerplate.git",
|
|
10
|
+
"directory": "packages/create-api"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/Frozen-Crow/api-boilerplate#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/Frozen-Crow/api-boilerplate/issues"
|
|
15
|
+
},
|
|
7
16
|
"keywords": [
|
|
8
17
|
"feathers",
|
|
9
18
|
"scaffold",
|
|
@@ -19,6 +28,7 @@
|
|
|
19
28
|
},
|
|
20
29
|
"files": [
|
|
21
30
|
"bin",
|
|
31
|
+
"lib",
|
|
22
32
|
"template"
|
|
23
33
|
],
|
|
24
34
|
"scripts": {
|
package/template/README.md
CHANGED
|
@@ -24,29 +24,29 @@ Configuration uses the Feathers config module (no `.env` files):
|
|
|
24
24
|
- `config/custom-environment-variables.json` — maps env vars (`AUTH_SECRET`,
|
|
25
25
|
`MONGODB_URI`, `PORT`, …) onto config for production.
|
|
26
26
|
|
|
27
|
-
Generate a fresh secret any time with `npm run secret -- --write` (
|
|
28
|
-
|
|
27
|
+
Generate a fresh secret any time with `npm run secret -- --write` (updates
|
|
28
|
+
`config/local.json`), or set `AUTH_SECRET` in the environment for production.
|
|
29
29
|
|
|
30
30
|
## Where things live
|
|
31
31
|
|
|
32
32
|
- `src/app.ts` — builds the app with `createConfiguredApp()` from
|
|
33
|
-
`@frozencrow/api-core
|
|
34
|
-
- `src/services/
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
33
|
+
`@frozencrow/api-core`.
|
|
34
|
+
- `src/services/index.ts` — registers your services. This is where scaffolded
|
|
35
|
+
and generated services get wired in.
|
|
36
|
+
- `src/services/<name>/` — each service is three files: a `.schema.ts`, a
|
|
37
|
+
`.class.ts`, and a registration file that calls `generateDefaultHooks({ schema })`.
|
|
38
38
|
|
|
39
|
-
## Generate services
|
|
39
|
+
## Generate more services
|
|
40
40
|
|
|
41
|
-
The `frozencrow` CLI ships with `@frozencrow/api-core
|
|
42
|
-
pattern instead of writing it by hand:
|
|
41
|
+
The `frozencrow` CLI ships with `@frozencrow/api-core`:
|
|
43
42
|
|
|
44
43
|
```bash
|
|
45
44
|
npx frozencrow generate service invoices --fields "amount:number,paid?:boolean" --wire
|
|
46
45
|
# shortcuts: npm run generate -- service invoices ... npm run secret
|
|
47
46
|
```
|
|
48
47
|
|
|
49
|
-
|
|
48
|
+
`--wire` also registers the service in your app. See the
|
|
49
|
+
[@frozencrow/api-core CLI docs](https://www.npmjs.com/package/@frozencrow/api-core#cli)
|
|
50
50
|
for all commands and options.
|
|
51
51
|
|
|
52
52
|
## What you get from the core
|
package/template/package.json
CHANGED
package/template/src/app.ts
CHANGED
|
@@ -1,15 +1,14 @@
|
|
|
1
1
|
import { createConfiguredApp } from '@frozencrow/api-core'
|
|
2
2
|
|
|
3
|
-
import {
|
|
3
|
+
import { services } from './services'
|
|
4
4
|
|
|
5
5
|
// Build a fully-configured API from the core. Configuration is loaded from the
|
|
6
6
|
// Feathers config module (config/*.json, config/local.json for secrets, and env
|
|
7
7
|
// vars mapped in config/custom-environment-variables.json) — no .env files.
|
|
8
8
|
//
|
|
9
9
|
// Everything (auth, RBAC, multitenancy, users/organizations/roles/invites/
|
|
10
|
-
// verifications) comes from @frozencrow/api-core;
|
|
11
|
-
// services
|
|
10
|
+
// verifications) comes from @frozencrow/api-core; register your own services in
|
|
11
|
+
// src/services/index.ts.
|
|
12
12
|
export const app = createConfiguredApp()
|
|
13
13
|
|
|
14
|
-
|
|
15
|
-
app.configure(widgets)
|
|
14
|
+
app.configure(services)
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Application } from '@frozencrow/api-core'
|
|
2
|
+
|
|
3
|
+
import { widgets } from './widgets/widgets'
|
|
4
|
+
|
|
5
|
+
// Register your services here. Generate new ones with:
|
|
6
|
+
// npx frozencrow generate service <name>
|
|
7
|
+
export const services = (app: Application) => {
|
|
8
|
+
app.configure(widgets)
|
|
9
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import assert from 'assert'
|
|
2
|
+
import { app } from '../src/app'
|
|
3
|
+
|
|
4
|
+
const port = app.get('port')
|
|
5
|
+
const appUrl = `http://${app.get('host')}:${port}`
|
|
6
|
+
|
|
7
|
+
const asJson = (res: Response) => res.json() as Promise<any>
|
|
8
|
+
|
|
9
|
+
describe('authentication', () => {
|
|
10
|
+
let userId = ''
|
|
11
|
+
|
|
12
|
+
before(async () => {
|
|
13
|
+
await app.listen(port)
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
after(async () => {
|
|
17
|
+
if (userId) {
|
|
18
|
+
try {
|
|
19
|
+
await app.service('users').remove(userId)
|
|
20
|
+
} catch {
|
|
21
|
+
/* ignore cleanup errors */
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
await app.teardown()
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
it('registers and authenticates a user, hiding the password', async () => {
|
|
28
|
+
const creds = { email: `t-${Date.now()}@example.com`, password: 'supersecret' }
|
|
29
|
+
|
|
30
|
+
await fetch(`${appUrl}/users`, {
|
|
31
|
+
method: 'POST',
|
|
32
|
+
headers: { 'Content-Type': 'application/json' },
|
|
33
|
+
body: JSON.stringify(creds)
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
const res = await fetch(`${appUrl}/authentication`, {
|
|
37
|
+
method: 'POST',
|
|
38
|
+
headers: { 'Content-Type': 'application/json' },
|
|
39
|
+
body: JSON.stringify({ strategy: 'local', ...creds })
|
|
40
|
+
})
|
|
41
|
+
const data = await asJson(res)
|
|
42
|
+
|
|
43
|
+
assert.ok(data.accessToken, 'issues an access token')
|
|
44
|
+
assert.ok(data.user, 'returns the user')
|
|
45
|
+
assert.strictEqual(data.user.password, undefined, 'password is hidden to clients')
|
|
46
|
+
|
|
47
|
+
userId = data.user._id
|
|
48
|
+
})
|
|
49
|
+
})
|
|
@@ -1,54 +1,49 @@
|
|
|
1
1
|
import assert from 'assert'
|
|
2
2
|
import { app } from '../src/app'
|
|
3
3
|
|
|
4
|
+
// Example test for the bundled `widgets` service. If you remove the widgets
|
|
5
|
+
// example, delete this file too.
|
|
6
|
+
|
|
4
7
|
const port = app.get('port')
|
|
5
8
|
const appUrl = `http://${app.get('host')}:${port}`
|
|
6
9
|
|
|
7
10
|
const asJson = (res: Response) => res.json() as Promise<any>
|
|
8
11
|
|
|
9
|
-
describe('
|
|
12
|
+
describe('widgets service', () => {
|
|
10
13
|
let accessToken = ''
|
|
11
14
|
let userId = ''
|
|
12
15
|
|
|
13
16
|
before(async () => {
|
|
14
17
|
await app.listen(port)
|
|
15
|
-
})
|
|
16
|
-
|
|
17
|
-
after(async () => {
|
|
18
|
-
if (userId) {
|
|
19
|
-
try {
|
|
20
|
-
await app.service('users').remove(userId)
|
|
21
|
-
} catch {
|
|
22
|
-
/* ignore cleanup errors */
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
await app.teardown()
|
|
26
|
-
})
|
|
27
|
-
|
|
28
|
-
it('registers and authenticates a user, hiding the password', async () => {
|
|
29
|
-
const creds = { email: `t-${Date.now()}@example.com`, password: 'supersecret' }
|
|
30
18
|
|
|
19
|
+
// Register + authenticate a user to exercise the tenant-scoped service.
|
|
20
|
+
const creds = { email: `w-${Date.now()}@example.com`, password: 'supersecret' }
|
|
31
21
|
await fetch(`${appUrl}/users`, {
|
|
32
22
|
method: 'POST',
|
|
33
23
|
headers: { 'Content-Type': 'application/json' },
|
|
34
24
|
body: JSON.stringify(creds)
|
|
35
25
|
})
|
|
36
|
-
|
|
37
26
|
const res = await fetch(`${appUrl}/authentication`, {
|
|
38
27
|
method: 'POST',
|
|
39
28
|
headers: { 'Content-Type': 'application/json' },
|
|
40
29
|
body: JSON.stringify({ strategy: 'local', ...creds })
|
|
41
30
|
})
|
|
42
31
|
const data = await asJson(res)
|
|
43
|
-
|
|
44
|
-
assert.ok(data.accessToken, 'issues an access token')
|
|
45
|
-
assert.ok(data.user, 'returns the user')
|
|
46
|
-
assert.strictEqual(data.user.password, undefined, 'password is hidden to clients')
|
|
47
|
-
|
|
48
32
|
accessToken = data.accessToken
|
|
49
33
|
userId = data.user._id
|
|
50
34
|
})
|
|
51
35
|
|
|
36
|
+
after(async () => {
|
|
37
|
+
if (userId) {
|
|
38
|
+
try {
|
|
39
|
+
await app.service('users').remove(userId)
|
|
40
|
+
} catch {
|
|
41
|
+
/* ignore cleanup errors */
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
await app.teardown()
|
|
45
|
+
})
|
|
46
|
+
|
|
52
47
|
it('creates a tenant-scoped widget through the custom service', async () => {
|
|
53
48
|
const res = await fetch(`${appUrl}/widgets`, {
|
|
54
49
|
method: 'POST',
|