@frozencrow/create-api 0.1.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 +34 -0
- package/bin/create-api.js +110 -0
- package/package.json +30 -0
- package/template/.dockerignore +4 -0
- package/template/.env.example +14 -0
- package/template/Dockerfile +25 -0
- package/template/README.md +42 -0
- package/template/docker-compose.yml +37 -0
- package/template/gitignore +4 -0
- package/template/package.json +35 -0
- package/template/public/index.html +10 -0
- package/template/src/app.ts +23 -0
- package/template/src/index.ts +14 -0
- package/template/src/services/widgets/widgets.class.ts +22 -0
- package/template/src/services/widgets/widgets.schema.ts +66 -0
- package/template/src/services/widgets/widgets.ts +54 -0
- package/template/test/app.test.ts +29 -0
- package/template/test/client.test.ts +69 -0
- package/template/tsconfig.json +26 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Eric Uldall
|
|
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
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# @frozencrow/create-api
|
|
2
|
+
|
|
3
|
+
Scaffold a new API project powered by
|
|
4
|
+
[`@frozencrow/api-core`](https://www.npmjs.com/package/@frozencrow/api-core).
|
|
5
|
+
|
|
6
|
+
## Usage
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
npm create @frozencrow/api my-app
|
|
10
|
+
# or
|
|
11
|
+
npx @frozencrow/create-api my-app
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
This creates `my-app/` from the bundled template, then:
|
|
15
|
+
|
|
16
|
+
- sets the project's package name,
|
|
17
|
+
- generates a strong `AUTH_SECRET` and writes a ready-to-edit `.env`,
|
|
18
|
+
- points `MONGODB_URI` at a database named after your project.
|
|
19
|
+
|
|
20
|
+
Then:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
cd my-app
|
|
24
|
+
npm install
|
|
25
|
+
npm run dev
|
|
26
|
+
```
|
|
27
|
+
|
|
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
|
+
## License
|
|
33
|
+
|
|
34
|
+
MIT
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Scaffolder for @frozencrow/api-core based projects.
|
|
6
|
+
*
|
|
7
|
+
* npm create @frozencrow/api my-app
|
|
8
|
+
* npx @frozencrow/create-api my-app
|
|
9
|
+
*
|
|
10
|
+
* Copies the bundled template, renames the project, generates a strong
|
|
11
|
+
* AUTH_SECRET, and writes a ready-to-edit .env. Zero runtime dependencies.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const fs = require('fs')
|
|
15
|
+
const path = require('path')
|
|
16
|
+
const crypto = require('crypto')
|
|
17
|
+
const readline = require('readline')
|
|
18
|
+
|
|
19
|
+
const TEMPLATE_DIR = path.join(__dirname, '..', 'template')
|
|
20
|
+
|
|
21
|
+
// Files that must be renamed on copy (npm strips/renames some dotfiles in
|
|
22
|
+
// published packages, so we ship them dot-less).
|
|
23
|
+
const RENAME_ON_COPY = { gitignore: '.gitignore' }
|
|
24
|
+
|
|
25
|
+
function isValidPackageName(name) {
|
|
26
|
+
return /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(name)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function copyDir(src, dest) {
|
|
30
|
+
fs.mkdirSync(dest, { recursive: true })
|
|
31
|
+
for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
|
|
32
|
+
if (entry.name === 'node_modules' || entry.name === 'lib') continue
|
|
33
|
+
const srcPath = path.join(src, entry.name)
|
|
34
|
+
const destName = RENAME_ON_COPY[entry.name] || entry.name
|
|
35
|
+
const destPath = path.join(dest, destName)
|
|
36
|
+
if (entry.isDirectory()) {
|
|
37
|
+
copyDir(srcPath, destPath)
|
|
38
|
+
} else {
|
|
39
|
+
fs.copyFileSync(srcPath, destPath)
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function ask(question) {
|
|
45
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
|
|
46
|
+
return new Promise((resolve) => rl.question(question, (answer) => {
|
|
47
|
+
rl.close()
|
|
48
|
+
resolve(answer.trim())
|
|
49
|
+
}))
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function main() {
|
|
53
|
+
let projectName = process.argv[2]
|
|
54
|
+
|
|
55
|
+
if (!projectName) {
|
|
56
|
+
projectName = await ask('Project name: ')
|
|
57
|
+
}
|
|
58
|
+
if (!projectName) {
|
|
59
|
+
console.error('Error: a project name is required.')
|
|
60
|
+
process.exit(1)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const targetDir = path.resolve(process.cwd(), projectName)
|
|
64
|
+
const pkgName = path.basename(projectName)
|
|
65
|
+
|
|
66
|
+
if (!isValidPackageName(pkgName)) {
|
|
67
|
+
console.error(`Error: "${pkgName}" is not a valid npm package name.`)
|
|
68
|
+
process.exit(1)
|
|
69
|
+
}
|
|
70
|
+
if (fs.existsSync(targetDir) && fs.readdirSync(targetDir).length > 0) {
|
|
71
|
+
console.error(`Error: directory "${projectName}" already exists and is not empty.`)
|
|
72
|
+
process.exit(1)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
console.log(`\nCreating a new API in ${targetDir} ...`)
|
|
76
|
+
copyDir(TEMPLATE_DIR, targetDir)
|
|
77
|
+
|
|
78
|
+
// 1. Set the package name.
|
|
79
|
+
const pkgPath = path.join(targetDir, 'package.json')
|
|
80
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'))
|
|
81
|
+
pkg.name = pkgName
|
|
82
|
+
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 4) + '\n')
|
|
83
|
+
|
|
84
|
+
// 2. Generate a strong secret and a real .env from the example.
|
|
85
|
+
const secret = crypto.randomBytes(48).toString('base64url')
|
|
86
|
+
const envExamplePath = path.join(targetDir, '.env.example')
|
|
87
|
+
let env = fs.readFileSync(envExamplePath, 'utf8')
|
|
88
|
+
env = env
|
|
89
|
+
.replace(/^APP_NAME=.*$/m, `APP_NAME=${pkgName}`)
|
|
90
|
+
.replace(/^AUTH_SECRET=.*$/m, `AUTH_SECRET=${secret}`)
|
|
91
|
+
.replace(/mongodb:\/\/localhost:27017\/my-api/g, `mongodb://localhost:27017/${pkgName}`)
|
|
92
|
+
fs.writeFileSync(path.join(targetDir, '.env'), env)
|
|
93
|
+
|
|
94
|
+
console.log(`
|
|
95
|
+
Done! Next steps:
|
|
96
|
+
|
|
97
|
+
cd ${projectName}
|
|
98
|
+
npm install
|
|
99
|
+
npm run dev
|
|
100
|
+
|
|
101
|
+
A strong AUTH_SECRET has been generated in .env. Point MONGODB_URI at your
|
|
102
|
+
database, then add your own services under src/services (see src/services/widgets
|
|
103
|
+
for the pattern).
|
|
104
|
+
`)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
main().catch((err) => {
|
|
108
|
+
console.error(err)
|
|
109
|
+
process.exit(1)
|
|
110
|
+
})
|
package/package.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@frozencrow/create-api",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Scaffold a new API project powered by @frozencrow/api-core",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Eric Uldall",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"feathers",
|
|
9
|
+
"scaffold",
|
|
10
|
+
"generator",
|
|
11
|
+
"create",
|
|
12
|
+
"api"
|
|
13
|
+
],
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">= 20.0.0"
|
|
16
|
+
},
|
|
17
|
+
"bin": {
|
|
18
|
+
"create-api": "bin/create-api.js"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"bin",
|
|
22
|
+
"template"
|
|
23
|
+
],
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "node -e \"process.exit(0)\""
|
|
26
|
+
},
|
|
27
|
+
"publishConfig": {
|
|
28
|
+
"access": "public"
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# Copy to .env and adjust. `npm create @frozencrow/api` generates a real AUTH_SECRET for you.
|
|
2
|
+
APP_NAME=My API
|
|
3
|
+
HOST=localhost
|
|
4
|
+
PORT=3030
|
|
5
|
+
|
|
6
|
+
# MongoDB connection string
|
|
7
|
+
MONGODB_URI=mongodb://localhost:27017/my-api
|
|
8
|
+
|
|
9
|
+
# JWT signing secret. MUST be a strong random value (>= 32 chars) in production.
|
|
10
|
+
AUTH_SECRET=please-change-me-to-a-random-32-plus-character-string
|
|
11
|
+
|
|
12
|
+
# Frontend URL (used in emails) and allowed CORS origins (comma-separated)
|
|
13
|
+
CLIENT_HOST=http://localhost:5173
|
|
14
|
+
ORIGINS=http://localhost:5173
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# Build stage
|
|
2
|
+
FROM node:20-alpine AS builder
|
|
3
|
+
|
|
4
|
+
WORKDIR /app
|
|
5
|
+
|
|
6
|
+
COPY package*.json ./
|
|
7
|
+
RUN npm ci
|
|
8
|
+
|
|
9
|
+
COPY . .
|
|
10
|
+
RUN npm run compile
|
|
11
|
+
|
|
12
|
+
# Production stage
|
|
13
|
+
FROM node:20-alpine
|
|
14
|
+
|
|
15
|
+
WORKDIR /app
|
|
16
|
+
|
|
17
|
+
COPY package*.json ./
|
|
18
|
+
RUN npm ci --omit=dev
|
|
19
|
+
|
|
20
|
+
COPY --from=builder /app/lib ./lib
|
|
21
|
+
COPY --from=builder /app/public ./public
|
|
22
|
+
|
|
23
|
+
EXPOSE 3030
|
|
24
|
+
|
|
25
|
+
CMD ["npm", "start"]
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# My API
|
|
2
|
+
|
|
3
|
+
An API built on [`@frozencrow/api-core`](https://www.npmjs.com/package/@frozencrow/api-core) —
|
|
4
|
+
authentication, RBAC, and multitenant (organization) access control out of the box.
|
|
5
|
+
|
|
6
|
+
## Getting started
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
npm install
|
|
10
|
+
cp .env.example .env # then set a strong AUTH_SECRET
|
|
11
|
+
npm run dev
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Requires a MongoDB instance (see `docker-compose.yml` for a local stack with
|
|
15
|
+
MongoDB + smtp4dev).
|
|
16
|
+
|
|
17
|
+
## Where things live
|
|
18
|
+
|
|
19
|
+
- `src/app.ts` — builds the app with `createApp(...)` from `@frozencrow/api-core`
|
|
20
|
+
and registers your own services.
|
|
21
|
+
- `src/services/widgets/` — an example multitenant service. Copy this folder as
|
|
22
|
+
the pattern for new resources: a `.schema.ts`, a `.class.ts`, and a registration
|
|
23
|
+
file that calls `generateDefaultHooks({ schema })`.
|
|
24
|
+
|
|
25
|
+
## What you get from the core
|
|
26
|
+
|
|
27
|
+
`users`, `organizations`, `roles`, `invites`, and `verifications` services with
|
|
28
|
+
local + Google + API-key auth, JWT, role-based permissions (`<path>:<method>`),
|
|
29
|
+
and per-organization data isolation. See the `@frozencrow/api-core` README for
|
|
30
|
+
the full configuration surface and security model.
|
|
31
|
+
|
|
32
|
+
## Testing
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
npm test # needs a MongoDB on localhost:27017
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Production
|
|
39
|
+
|
|
40
|
+
- Set a strong `AUTH_SECRET` (the app refuses to boot in production without one).
|
|
41
|
+
- Set `ORIGINS` to your allowed browser origins.
|
|
42
|
+
- `npm run compile && npm start`, or build the Docker image.
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
services:
|
|
2
|
+
api:
|
|
3
|
+
build: .
|
|
4
|
+
ports:
|
|
5
|
+
- "3030:3030"
|
|
6
|
+
environment:
|
|
7
|
+
- NODE_ENV=development
|
|
8
|
+
- PORT=3030
|
|
9
|
+
# Connect to the mongodb service on its in-network port (27017),
|
|
10
|
+
# not the host-published one.
|
|
11
|
+
- MONGODB_URI=mongodb://mongodb:27017/my-api
|
|
12
|
+
- MAIL_HOST=smtp4dev
|
|
13
|
+
- MAIL_PORT=25
|
|
14
|
+
- ORIGINS=http://localhost:5173
|
|
15
|
+
# Override with a strong value in any non-local environment.
|
|
16
|
+
- AUTH_SECRET=dev-only-secret-change-me-32-chars!!
|
|
17
|
+
depends_on:
|
|
18
|
+
- mongodb
|
|
19
|
+
- smtp4dev
|
|
20
|
+
|
|
21
|
+
mongodb:
|
|
22
|
+
image: mongo:7
|
|
23
|
+
ports:
|
|
24
|
+
- "27017:27017"
|
|
25
|
+
volumes:
|
|
26
|
+
- mongodb_data:/data/db
|
|
27
|
+
|
|
28
|
+
smtp4dev:
|
|
29
|
+
image: rnwood/smtp4dev:latest
|
|
30
|
+
ports:
|
|
31
|
+
- "8888:80" # Web UI
|
|
32
|
+
- "2526:25" # SMTP Port (external)
|
|
33
|
+
environment:
|
|
34
|
+
- ServerOptions__HostName=smtp4dev
|
|
35
|
+
|
|
36
|
+
volumes:
|
|
37
|
+
mongodb_data:
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "my-api",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "API built on @frozencrow/api-core",
|
|
5
|
+
"private": true,
|
|
6
|
+
"engines": {
|
|
7
|
+
"node": ">= 20.0.0"
|
|
8
|
+
},
|
|
9
|
+
"scripts": {
|
|
10
|
+
"dev": "nodemon -x ts-node src/index.ts",
|
|
11
|
+
"compile": "shx rm -rf lib/ && tsc",
|
|
12
|
+
"start": "node lib/",
|
|
13
|
+
"mocha": "cross-env NODE_ENV=test PORT=8998 ORIGINS=http://localhost:5173 MONGODB_URI=mongodb://localhost:27017/my-api-test AUTH_SECRET=test-secret-least-32-characters-long!! mocha test/ --require ts-node/register --recursive --extension .ts --exit",
|
|
14
|
+
"test": "npm run mocha"
|
|
15
|
+
},
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"@frozencrow/api-core": "^0.1.0",
|
|
18
|
+
"@feathersjs/feathers": "^5.0.37",
|
|
19
|
+
"@feathersjs/mongodb": "^5.0.37",
|
|
20
|
+
"@feathersjs/schema": "^5.0.37",
|
|
21
|
+
"@feathersjs/typebox": "^5.0.37",
|
|
22
|
+
"dotenv": "^16.4.5"
|
|
23
|
+
},
|
|
24
|
+
"devDependencies": {
|
|
25
|
+
"@feathersjs/rest-client": "^5.0.37",
|
|
26
|
+
"@types/mocha": "^10.0.10",
|
|
27
|
+
"@types/node": "^24.10.4",
|
|
28
|
+
"cross-env": "^10.1.0",
|
|
29
|
+
"mocha": "^11.7.5",
|
|
30
|
+
"nodemon": "^3.1.11",
|
|
31
|
+
"shx": "^0.4.0",
|
|
32
|
+
"ts-node": "^10.9.2",
|
|
33
|
+
"typescript": "^5.9.3"
|
|
34
|
+
}
|
|
35
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import 'dotenv/config'
|
|
2
|
+
import { join } from 'path'
|
|
3
|
+
import { createApp } from '@frozencrow/api-core'
|
|
4
|
+
|
|
5
|
+
import { widgets } from './services/widgets/widgets'
|
|
6
|
+
|
|
7
|
+
// Build a fully-configured API from the core. Everything (auth, RBAC,
|
|
8
|
+
// multitenancy, users/organizations/roles/invites/verifications) comes from
|
|
9
|
+
// @frozencrow/api-core; you extend it with your own services below.
|
|
10
|
+
export const app = createApp({
|
|
11
|
+
appName: process.env.APP_NAME || 'My API',
|
|
12
|
+
host: process.env.HOST || 'localhost',
|
|
13
|
+
port: Number(process.env.PORT) || 3030,
|
|
14
|
+
public: join(__dirname, '..', 'public'),
|
|
15
|
+
mongodb: process.env.MONGODB_URI || 'mongodb://localhost:27017/my-api',
|
|
16
|
+
authSecret: process.env.AUTH_SECRET || 'dev-only-secret-change-me-32-chars!!',
|
|
17
|
+
clientHost: process.env.CLIENT_HOST || 'http://localhost:5173',
|
|
18
|
+
origins: (process.env.ORIGINS || 'http://localhost:5173').split(',').filter(Boolean),
|
|
19
|
+
seed: true
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
// --- Register your own services on top of the core ---
|
|
23
|
+
app.configure(widgets)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { app } from './app'
|
|
2
|
+
|
|
3
|
+
const port = app.get('port')
|
|
4
|
+
const host = app.get('host')
|
|
5
|
+
|
|
6
|
+
process.on('unhandledRejection', (reason) => {
|
|
7
|
+
// eslint-disable-next-line no-console
|
|
8
|
+
console.error('Unhandled Rejection', reason)
|
|
9
|
+
})
|
|
10
|
+
|
|
11
|
+
app.listen(port).then(() => {
|
|
12
|
+
// eslint-disable-next-line no-console
|
|
13
|
+
console.log(`API listening on http://${host}:${port}`)
|
|
14
|
+
})
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Params } from '@feathersjs/feathers'
|
|
2
|
+
import { MongoDBService } from '@feathersjs/mongodb'
|
|
3
|
+
import type { MongoDBAdapterParams, MongoDBAdapterOptions } from '@feathersjs/mongodb'
|
|
4
|
+
import type { Application } from '@frozencrow/api-core'
|
|
5
|
+
|
|
6
|
+
import type { Widget, WidgetData, WidgetPatch, WidgetQuery } from './widgets.schema'
|
|
7
|
+
|
|
8
|
+
export interface WidgetParams extends MongoDBAdapterParams<WidgetQuery> {}
|
|
9
|
+
|
|
10
|
+
export class WidgetService<ServiceParams extends Params = WidgetParams> extends MongoDBService<
|
|
11
|
+
Widget,
|
|
12
|
+
WidgetData,
|
|
13
|
+
WidgetParams,
|
|
14
|
+
WidgetPatch
|
|
15
|
+
> {}
|
|
16
|
+
|
|
17
|
+
export const getOptions = (app: Application): MongoDBAdapterOptions => {
|
|
18
|
+
return {
|
|
19
|
+
paginate: app.get('paginate'),
|
|
20
|
+
Model: (app.get('mongodbClient') as Promise<any>).then((db) => db.collection('widgets'))
|
|
21
|
+
}
|
|
22
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { resolve } from '@feathersjs/schema'
|
|
2
|
+
import { Type, getValidator, querySyntax, ObjectIdSchema } from '@feathersjs/typebox'
|
|
3
|
+
import type { Static } from '@feathersjs/typebox'
|
|
4
|
+
import { dataValidator, queryValidator } from '@frozencrow/api-core'
|
|
5
|
+
import type { HookContext } from '@frozencrow/api-core'
|
|
6
|
+
|
|
7
|
+
// A minimal multitenant resource. `organizationId` scopes it to the caller's
|
|
8
|
+
// active organization — that is enforced automatically by teamAccessControl
|
|
9
|
+
// (wired in via generateDefaultHooks in widgets.ts).
|
|
10
|
+
export const widgetSchema = Type.Object(
|
|
11
|
+
{
|
|
12
|
+
_id: ObjectIdSchema(),
|
|
13
|
+
name: Type.String(),
|
|
14
|
+
organizationId: ObjectIdSchema(),
|
|
15
|
+
createdAt: Type.Number(),
|
|
16
|
+
updatedAt: Type.Number()
|
|
17
|
+
},
|
|
18
|
+
{ $id: 'Widget', additionalProperties: false }
|
|
19
|
+
)
|
|
20
|
+
export type Widget = Static<typeof widgetSchema>
|
|
21
|
+
export const widgetResolver = resolve<Widget, HookContext>({})
|
|
22
|
+
export const widgetExternalResolver = resolve<Widget, HookContext>({})
|
|
23
|
+
|
|
24
|
+
// The client only supplies `name`; the rest are set by resolvers /
|
|
25
|
+
// teamAccessControl but must be permitted here so post-resolution validation
|
|
26
|
+
// passes (resolveData runs before validateData in generateDefaultHooks).
|
|
27
|
+
export const widgetDataSchema = Type.Intersect(
|
|
28
|
+
[
|
|
29
|
+
Type.Pick(widgetSchema, ['name']),
|
|
30
|
+
Type.Object({
|
|
31
|
+
organizationId: Type.Optional(ObjectIdSchema()),
|
|
32
|
+
createdAt: Type.Optional(Type.Number()),
|
|
33
|
+
updatedAt: Type.Optional(Type.Number())
|
|
34
|
+
})
|
|
35
|
+
],
|
|
36
|
+
{ $id: 'WidgetData' }
|
|
37
|
+
)
|
|
38
|
+
export type WidgetData = Static<typeof widgetDataSchema>
|
|
39
|
+
export const widgetDataValidator = getValidator(widgetDataSchema, dataValidator)
|
|
40
|
+
export const widgetDataResolver = resolve<Widget, HookContext>({
|
|
41
|
+
// teamAccessControl auto-assigns organizationId for non-admins; this fallback
|
|
42
|
+
// ensures it is always set (e.g. for admins) from the active organization.
|
|
43
|
+
organizationId: async (value, _data, context) =>
|
|
44
|
+
value || (context.params as any).user?.activeOrganization,
|
|
45
|
+
createdAt: async () => Date.now(),
|
|
46
|
+
updatedAt: async () => Date.now()
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
export const widgetPatchSchema = Type.Partial(
|
|
50
|
+
Type.Pick(widgetSchema, ['name', 'organizationId', 'createdAt', 'updatedAt']),
|
|
51
|
+
{ $id: 'WidgetPatch' }
|
|
52
|
+
)
|
|
53
|
+
export type WidgetPatch = Static<typeof widgetPatchSchema>
|
|
54
|
+
export const widgetPatchValidator = getValidator(widgetPatchSchema, dataValidator)
|
|
55
|
+
export const widgetPatchResolver = resolve<Widget, HookContext>({
|
|
56
|
+
updatedAt: async () => Date.now()
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
export const widgetQueryProperties = Type.Pick(widgetSchema, ['_id', 'name', 'organizationId', 'createdAt'])
|
|
60
|
+
export const widgetQuerySchema = Type.Intersect(
|
|
61
|
+
[querySyntax(widgetQueryProperties), Type.Object({}, { additionalProperties: false })],
|
|
62
|
+
{ additionalProperties: false }
|
|
63
|
+
)
|
|
64
|
+
export type WidgetQuery = Static<typeof widgetQuerySchema>
|
|
65
|
+
export const widgetQueryValidator = getValidator(widgetQuerySchema, queryValidator)
|
|
66
|
+
export const widgetQueryResolver = resolve<WidgetQuery, HookContext>({})
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { generateDefaultHooks } from '@frozencrow/api-core'
|
|
2
|
+
import type { Application } from '@frozencrow/api-core'
|
|
3
|
+
|
|
4
|
+
import { WidgetService, getOptions } from './widgets.class'
|
|
5
|
+
import {
|
|
6
|
+
widgetDataValidator,
|
|
7
|
+
widgetPatchValidator,
|
|
8
|
+
widgetQueryValidator,
|
|
9
|
+
widgetResolver,
|
|
10
|
+
widgetExternalResolver,
|
|
11
|
+
widgetDataResolver,
|
|
12
|
+
widgetPatchResolver,
|
|
13
|
+
widgetQueryResolver
|
|
14
|
+
} from './widgets.schema'
|
|
15
|
+
|
|
16
|
+
export const widgetPath = 'widgets'
|
|
17
|
+
export const widgetMethods = ['find', 'get', 'create', 'patch', 'remove'] as const
|
|
18
|
+
|
|
19
|
+
// Register the service's types with the core so `app.use('widgets', ...)` and
|
|
20
|
+
// `app.service('widgets')` are fully typed. This is how you extend the core's
|
|
21
|
+
// service map from a consumer app. (Type-only declaration — erased at build.)
|
|
22
|
+
declare module '@frozencrow/api-core/lib/declarations' {
|
|
23
|
+
interface ServiceTypes {
|
|
24
|
+
widgets: WidgetService
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Registering a custom service is the same three steps for every resource:
|
|
29
|
+
// 1. app.use(path, new Service(...))
|
|
30
|
+
// 2. generateDefaultHooks({ schema, ... }) — brings JWT auth, multitenant
|
|
31
|
+
// teamAccessControl (permission `widgets:<method>`), validation, resolvers,
|
|
32
|
+
// virtual-prop discarding, and error logging.
|
|
33
|
+
// 3. app.service(path).hooks(...)
|
|
34
|
+
export const widgets = (app: Application) => {
|
|
35
|
+
app.use(widgetPath, new WidgetService(getOptions(app)), {
|
|
36
|
+
methods: [...widgetMethods],
|
|
37
|
+
events: []
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
app.service(widgetPath).hooks(
|
|
41
|
+
generateDefaultHooks({
|
|
42
|
+
schema: {
|
|
43
|
+
dataValidator: widgetDataValidator,
|
|
44
|
+
patchValidator: widgetPatchValidator,
|
|
45
|
+
queryValidator: widgetQueryValidator,
|
|
46
|
+
dataResolver: widgetDataResolver,
|
|
47
|
+
patchResolver: widgetPatchResolver,
|
|
48
|
+
queryResolver: widgetQueryResolver,
|
|
49
|
+
externalResolver: widgetExternalResolver,
|
|
50
|
+
resultResolver: widgetResolver
|
|
51
|
+
}
|
|
52
|
+
})
|
|
53
|
+
)
|
|
54
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
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
|
+
describe('Feathers application tests', () => {
|
|
8
|
+
before(async () => {
|
|
9
|
+
await app.listen(port)
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
after(async () => {
|
|
13
|
+
await app.teardown()
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
it('starts and shows the index page', async () => {
|
|
17
|
+
const response = await fetch(appUrl)
|
|
18
|
+
const text = await response.text()
|
|
19
|
+
assert.ok(text.indexOf('API is running') !== -1)
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
it('shows a 404 JSON error', async () => {
|
|
23
|
+
const response = await fetch(`${appUrl}/path/to/nowhere`)
|
|
24
|
+
assert.strictEqual(response.status, 404)
|
|
25
|
+
const data = await response.json() as any
|
|
26
|
+
assert.strictEqual(data.code, 404)
|
|
27
|
+
assert.strictEqual(data.name, 'NotFound')
|
|
28
|
+
})
|
|
29
|
+
})
|
|
@@ -0,0 +1,69 @@
|
|
|
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('API core integration', () => {
|
|
10
|
+
let accessToken = ''
|
|
11
|
+
let userId = ''
|
|
12
|
+
|
|
13
|
+
before(async () => {
|
|
14
|
+
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
|
+
|
|
31
|
+
await fetch(`${appUrl}/users`, {
|
|
32
|
+
method: 'POST',
|
|
33
|
+
headers: { 'Content-Type': 'application/json' },
|
|
34
|
+
body: JSON.stringify(creds)
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
const res = await fetch(`${appUrl}/authentication`, {
|
|
38
|
+
method: 'POST',
|
|
39
|
+
headers: { 'Content-Type': 'application/json' },
|
|
40
|
+
body: JSON.stringify({ strategy: 'local', ...creds })
|
|
41
|
+
})
|
|
42
|
+
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
|
+
accessToken = data.accessToken
|
|
49
|
+
userId = data.user._id
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it('creates a tenant-scoped widget through the custom service', async () => {
|
|
53
|
+
const res = await fetch(`${appUrl}/widgets`, {
|
|
54
|
+
method: 'POST',
|
|
55
|
+
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${accessToken}` },
|
|
56
|
+
body: JSON.stringify({ name: 'Test Widget' })
|
|
57
|
+
})
|
|
58
|
+
const widget = await asJson(res)
|
|
59
|
+
|
|
60
|
+
assert.strictEqual(res.status, 201, 'widget created')
|
|
61
|
+
assert.strictEqual(widget.name, 'Test Widget')
|
|
62
|
+
assert.ok(widget.organizationId, 'widget is scoped to an organization')
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
it('rejects unauthenticated widget access', async () => {
|
|
66
|
+
const res = await fetch(`${appUrl}/widgets`)
|
|
67
|
+
assert.ok(res.status === 401 || res.status === 403, `expected auth error, got ${res.status}`)
|
|
68
|
+
})
|
|
69
|
+
})
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
{
|
|
2
|
+
"ts-node": {
|
|
3
|
+
"files": true
|
|
4
|
+
},
|
|
5
|
+
"compilerOptions": {
|
|
6
|
+
"target": "es2020",
|
|
7
|
+
"module": "commonjs",
|
|
8
|
+
"outDir": "./lib",
|
|
9
|
+
"rootDir": "./src",
|
|
10
|
+
"declaration": true,
|
|
11
|
+
"strict": true,
|
|
12
|
+
"esModuleInterop": true,
|
|
13
|
+
"sourceMap": true,
|
|
14
|
+
"skipLibCheck": true,
|
|
15
|
+
"moduleResolution": "node",
|
|
16
|
+
"resolveJsonModule": true
|
|
17
|
+
},
|
|
18
|
+
"include": [
|
|
19
|
+
"src"
|
|
20
|
+
],
|
|
21
|
+
"exclude": [
|
|
22
|
+
"test",
|
|
23
|
+
"lib",
|
|
24
|
+
"node_modules"
|
|
25
|
+
]
|
|
26
|
+
}
|