Skip to content

Commit 928842b

Browse files
chore: wip
1 parent affa6eb commit 928842b

File tree

10 files changed

+184
-29
lines changed

10 files changed

+184
-29
lines changed

app/Models/Subscriber.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,12 @@ export default {
1414
// defaults to a count of 10
1515
count: 10,
1616
},
17+
18+
useApi: {
19+
uri: 'subscribers', // your-url.com/api/users
20+
middleware: ['auth'], // defaults to `[]`
21+
routes: ['index', 'update', 'store', 'destroy', 'show'],
22+
},
1723
},
1824

1925
attributes: {

storage/framework/core/actions/src/orm/generate-model.ts

Lines changed: 53 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -22,23 +22,57 @@ export interface ModelElement {
2222
await initiateModelGeneration()
2323
await setKyselyTypes()
2424

25-
async function generateApiRoutes(model: Model) {
26-
if (model.traits?.useApi) {
27-
let routeString = `import { route } from '@stacksjs/router'\n\n\n`
28-
const apiRoutes = model.traits?.useApi?.routes
29-
30-
if (apiRoutes?.length) {
31-
for (const apiRoute of apiRoutes) {
32-
await writeOrmActions(apiRoute, model)
33-
routeString += await writeApiRoutes(apiRoute, model)
25+
async function generateApiRoutes(modelFiles: string[]) {
26+
const file = Bun.file(path.projectStoragePath(`framework/orm/routes.ts`))
27+
const writer = file.writer()
28+
let routeString = `import { route } from '@stacksjs/router'\n\n\n`
29+
30+
for (const modelFile of modelFiles) {
31+
log.debug(`Processing model file: ${modelFile}`)
32+
33+
const model = (await import(modelFile)).default as Model
34+
35+
if (model.traits?.useApi) {
36+
const apiRoutes = model.traits?.useApi?.routes
37+
const middlewares = model.traits.useApi?.middleware
38+
let middlewareString = `.middleware([`
39+
40+
if (middlewares.length) {
41+
for (let i = 0; i < middlewares.length; i++) {
42+
middlewareString += `'${middlewares[i]}'`
43+
44+
if (i < middlewares.length - 1) {
45+
middlewareString += ','
46+
}
47+
}
48+
49+
}
50+
51+
middlewareString += `])`
52+
53+
if (apiRoutes?.length) {
54+
for (const apiRoute of apiRoutes) {
55+
await writeOrmActions(apiRoute, model)
56+
57+
if (apiRoute === 'index') routeString += `await route.get('${model.table}', 'Actions/${model.name}IndexOrmAction')${middlewareString}\n\n`
58+
59+
if (apiRoute === 'store') routeString += `await route.post('${model.table}', 'Actions/${model.name}StoreOrmAction')${middlewareString}\n\n`
60+
61+
if (apiRoute === 'update')
62+
routeString += `await route.patch('${model.table}/{id}', 'Actions/${model.name}UpdateOrmAction')${middlewareString}\n\n`
63+
64+
if (apiRoute === 'show')
65+
routeString += `await route.get('${model.table}/{id}', 'Actions/${model.name}ShowOrmAction')${middlewareString}\n\n`
66+
67+
if (apiRoute === 'destroy')
68+
routeString += `await route.delete('${model.table}/{id}', 'Actions/${model.name}DestroyOrmAction')${middlewareString}\n\n`
69+
}
3470
}
3571
}
36-
37-
const file = Bun.file(path.projectStoragePath(`framework/orm/routes.ts`))
38-
const writer = file.writer()
39-
writer.write(routeString)
40-
await writer.end()
4172
}
73+
74+
writer.write(routeString)
75+
await writer.end()
4276
}
4377

4478
async function writeModelNames() {
@@ -173,15 +207,15 @@ async function initiateModelGeneration(): Promise<void> {
173207

174208
const modelFiles = glob.sync(path.userModelsPath('*.ts'))
175209

210+
await generateApiRoutes(modelFiles)
211+
176212
for (const modelFile of modelFiles) {
177213
log.debug(`Processing model file: ${modelFile}`)
178214

179215
const model = (await import(modelFile)).default as Model
180216
const tableName = await modelTableName(model)
181217
const modelName = path.basename(modelFile, '.ts')
182218

183-
await generateApiRoutes(model)
184-
185219
const file = Bun.file(path.projectStoragePath(`framework/orm/src/models/${modelName}.ts`))
186220
const fields = await extractFields(model, modelFile)
187221
const classString = await generateModelString(tableName, model, fields)
@@ -247,10 +281,13 @@ async function deleteExistingModels() {
247281

248282
async function deleteExistingOrmActions() {
249283
const ormPaths = glob.sync(path.projectStoragePath(`framework/orm/Actions/*.ts`))
284+
const routes = path.projectStoragePath(`framework/orm/routes`)
250285

251286
for (const ormPath of ormPaths) {
252287
if (fs.existsSync(ormPath)) await Bun.$`rm ${ormPath}`
253288
}
289+
290+
if (fs.existsSync(routes)) await Bun.$`rm ${routes}`
254291
}
255292

256293
async function deleteExistingModelNameTypes() {

storage/framework/core/router/src/router.ts

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -52,12 +52,10 @@ export class Router implements RouterInterface {
5252
return this
5353
}
5454

55-
public async get(path: Route['url'], callback: Route['callback']): Promise<this> {
55+
public get(path: Route['url'], callback: Route['callback']): this {
5656
this.path = this.normalizePath(path)
5757
log.debug(`Normalized Path: ${this.path}`)
5858

59-
// callback = await this.resolveCallback(callback)
60-
6159
const uri = this.prepareUri(this.path)
6260
log.debug(`Prepared URI: ${uri}`)
6361

@@ -123,11 +121,19 @@ export class Router implements RouterInterface {
123121
}
124122

125123
public post(path: Route['url'], callback: Route['callback']): this {
126-
return this.addRoute('POST', this.prepareUri(path), callback, 201)
124+
this.path = this.normalizePath(path)
125+
126+
const uri = this.prepareUri(this.path)
127+
128+
return this.addRoute('POST', uri, callback, 201)
127129
}
128130

129131
public view(path: Route['url'], callback: Route['callback']): this {
130-
return this.addRoute('GET', path, callback, 200)
132+
this.path = this.normalizePath(path)
133+
134+
const uri = this.prepareUri(this.path)
135+
136+
return this.addRoute('GET', uri, callback, 200)
131137
}
132138

133139
public redirect(path: Route['url'], callback: Route['callback'], _status?: RedirectCode): this {
@@ -139,11 +145,21 @@ export class Router implements RouterInterface {
139145
}
140146

141147
public patch(path: Route['url'], callback: Route['callback']): this {
142-
return this.addRoute('PATCH', this.prepareUri(path), callback, 202)
148+
this.path = this.normalizePath(path)
149+
log.debug(`Normalized Path: ${this.path}`)
150+
151+
const uri = this.prepareUri(this.path)
152+
log.debug(`Prepared URI: ${uri}`)
153+
154+
return this.addRoute('PATCH', uri, callback, 202)
143155
}
144156

145157
public put(path: Route['url'], callback: Route['callback']): this {
146-
return this.addRoute('PUT', this.prepareUri(path), callback, 202)
158+
this.path = this.normalizePath(path)
159+
160+
const uri = this.prepareUri(this.path)
161+
162+
return this.addRoute('PUT', uri, callback, 202)
147163
}
148164

149165
public group(options: string | RouteGroupOptions, callback?: () => void): this {

storage/framework/core/types/src/router.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ export interface RouteGroupOptions {
4949
type Prefix = string
5050

5151
export interface RouterInterface {
52-
get: (url: Route['url'], callback: Route['callback']) => Promise<this>
52+
get: (url: Route['url'], callback: Route['callback']) => this
5353
post: (url: Route['url'], callback: Route['callback']) => this
5454
view: (url: Route['url'], callback: Route['callback']) => this
5555
redirect: (url: Route['url'], callback: Route['callback'], status?: RedirectCode) => this
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { Action } from '@stacksjs/actions'
2+
import Subscriber from '../src/models/Subscriber'
3+
4+
import { request } from '@stacksjs/router'
5+
6+
export default new Action({
7+
name: 'Subscriber Destroy',
8+
description: 'Subscriber Destroy ORM Action',
9+
method: 'DELETE',
10+
async handle() {
11+
const id = request.getParam('id')
12+
13+
const model = await Subscriber.findOrFail(Number(id))
14+
15+
model.delete()
16+
17+
return 'Model deleted!'
18+
},
19+
})
20+
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { Action } from '@stacksjs/actions'
2+
import Subscriber from '../src/models/Subscriber'
3+
4+
import { request } from '@stacksjs/router'
5+
6+
export default new Action({
7+
name: 'Subscriber Index',
8+
description: 'Subscriber Index ORM Action',
9+
method: 'GET',
10+
async handle() {
11+
return await Subscriber.all()
12+
},
13+
})
14+
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { Action } from '@stacksjs/actions'
2+
import Subscriber from '../src/models/Subscriber'
3+
4+
import { request } from '@stacksjs/router'
5+
6+
export default new Action({
7+
name: 'Subscriber Show',
8+
description: 'Subscriber Show ORM Action',
9+
method: 'GET',
10+
async handle() {
11+
const id = await request.getParam('id')
12+
13+
return Subscriber.findOrFail(Number(id))
14+
},
15+
})
16+
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { Action } from '@stacksjs/actions'
2+
import Subscriber from '../src/models/Subscriber'
3+
4+
import { request } from '@stacksjs/router'
5+
6+
export default new Action({
7+
name: 'Subscriber Store',
8+
description: 'Subscriber Store ORM Action',
9+
method: 'POST',
10+
async handle() {
11+
const model = await Subscriber.create(request.all())
12+
13+
return model
14+
},
15+
})
16+
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { Action } from '@stacksjs/actions'
2+
import Subscriber from '../src/models/Subscriber'
3+
4+
import { request } from '@stacksjs/router'
5+
6+
export default new Action({
7+
name: 'Subscriber Update',
8+
description: 'Subscriber Update ORM Action',
9+
method: 'PATCH',
10+
async handle() {
11+
const id = request.getParam('id')
12+
13+
const model = await Subscriber.findOrFail(Number(id))
14+
15+
return model.update(request.all())
16+
},
17+
})
18+

storage/framework/orm/routes.ts

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,25 @@
11
import { route } from '@stacksjs/router'
22

33

4-
await route.get('users', 'Actions/UserIndexOrmAction')
4+
await route.get('subscribers', 'Actions/SubscriberIndexOrmAction').middleware(['auth'])
55

6-
await route.patch('users/{id}', 'Actions/UserUpdateOrmAction')
6+
await route.patch('subscribers/{id}', 'Actions/SubscriberUpdateOrmAction').middleware(['auth'])
77

8-
await route.post('users', 'Actions/UserStoreOrmAction')
8+
await route.post('subscribers', 'Actions/SubscriberStoreOrmAction').middleware(['auth'])
99

10-
await route.delete('users/{id}', 'Actions/UserDestroyOrmAction')
10+
await route.delete('subscribers/{id}', 'Actions/SubscriberDestroyOrmAction').middleware(['auth'])
1111

12-
await route.get('users/{id}', 'Actions/UserShowOrmAction')
12+
await route.get('subscribers/{id}', 'Actions/SubscriberShowOrmAction').middleware(['auth'])
13+
14+
await route.get('users', 'Actions/UserIndexOrmAction').middleware(['auth'])
15+
16+
await route.patch('users/{id}', 'Actions/UserUpdateOrmAction').middleware(['auth'])
17+
18+
await route.post('users', 'Actions/UserStoreOrmAction').middleware(['auth'])
19+
20+
await route.delete('users/{id}', 'Actions/UserDestroyOrmAction').middleware(['auth'])
21+
22+
await route.get('users/{id}', 'Actions/UserShowOrmAction').middleware(['auth'])
23+
24+
erShowOrmAction').middleware(['auth'])
1325

0 commit comments

Comments
 (0)