Skip to content

Commit 28ab7ec

Browse files
chore: wip
1 parent 294f3b7 commit 28ab7ec

File tree

4 files changed

+59
-48
lines changed

4 files changed

+59
-48
lines changed

routes/api.ts

Lines changed: 0 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +0,0 @@
1-
import { route } from '@stacksjs/router'
2-
3-
/**
4-
* This file is the entry point for your application's API routes.
5-
* The routes defined here are automatically registered. Last but
6-
* not least, you may also create any other `routes/*.ts` files.
7-
*
8-
* @see https://stacksjs.org/docs/routing
9-
*/
10-
11-
await route.get('/', () => 'hello world') // $APP_URL/api
12-
await route.get('/hello/world', () => 'hello world, buddy') // stacksjs.org/api/hello/world
13-
await route.get('/hello-world', () => {
14-
// $APP_URL/api/welcome
15-
return {
16-
// you may return an object as well
17-
data: 'hello world, friend',
18-
}
19-
})
20-
21-
await route.email('/welcome')
22-
await route.health() // adds an `/api/health` route
23-
24-
// await route.group('/some-path', async () => {...})
25-
// await route.action('/example') // equivalent to `route.get('/example', 'ExampleAction')`
26-
// await route.job('/example-two') // equivalent to `route.get('/example-two', 'ExampleTwoJob')`

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

Lines changed: 44 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,13 @@ await initiateModelGeneration()
2323
await setKyselyTypes()
2424

2525
async function generateApiRoutes(model: ModelDefault) {
26+
2627
let routeString = `import { route } from '@stacksjs/router'\n\n\n`
2728
if (model.default.traits?.useApi) {
2829
const apiRoutes = model.default.traits?.useApi?.routes
2930
if (apiRoutes.length) {
3031
for (const apiRoute of apiRoutes) {
32+
await writeOrmActions(apiRoute, model)
3133
routeString += await writeApiRoutes(apiRoute, model)
3234
}
3335
}
@@ -41,36 +43,61 @@ async function generateApiRoutes(model: ModelDefault) {
4143
}
4244
}
4345

44-
async function writeOrmActions(): Promise<void> {}
46+
async function writeOrmActions(apiRoute: string, model: ModelDefault): Promise<void> {
47+
const modelName = model.default.name
48+
const formattedApiRoute = apiRoute.charAt(0).toUpperCase() + apiRoute.slice(1)
49+
50+
let actionString = `import { Action } from '@stacksjs/actions'\n`
51+
actionString += `import ${modelName} from '../${modelName}'\n\n`
52+
53+
actionString += `export default new Action({
54+
name: '${modelName} ${formattedApiRoute}',
55+
description: '${modelName} ${formattedApiRoute} Orm Action',
56+
57+
handle() {
58+
return ${modelName}.find(1)
59+
},
60+
})
61+
`
62+
63+
const file = Bun.file(path.projectStoragePath(`framework/orm/Actions/${modelName}${formattedApiRoute}OrmAction.ts`))
64+
65+
const writer = file.writer()
66+
67+
writer.write(actionString)
68+
}
4569

4670
async function writeApiRoutes(
4771
apiRoute: string,
4872
model: ModelDefault,
4973
): Promise<string> {
5074
let routeString = ``
51-
const modelNameFormatted = model.default.name.toLowerCase()
75+
const tableName = model.default.table
5276
const modelName = model.default.name
5377

5478
if (apiRoute === 'index')
55-
routeString += `await route.get('${modelNameFormatted}', () => 'Actions/${modelName}IndexOrmAction')\n\n`
79+
routeString += `await route.get('${tableName}', () => 'Actions/${modelName}IndexOrmAction')\n\n`
5680

5781
if (apiRoute === 'store')
58-
routeString += `await route.post('${modelNameFormatted}', () => 'Actions/${modelName}StoreOrmAction')\n\n`
82+
routeString += `await route.post('${tableName}', () => 'Actions/${modelName}StoreOrmAction')\n\n`
5983

6084
if (apiRoute === 'update')
61-
routeString += `await route.patch('${modelNameFormatted}/{id}', () => 'Actions/${modelName}UpdateOrmAction')\n\n`
85+
routeString += `await route.patch('${tableName}/{id}', () => 'Actions/${modelName}UpdateOrmAction')\n\n`
6286

6387
if (apiRoute === 'show')
64-
routeString += `await route.get('${modelNameFormatted}/{id}', () => 'Actions/${modelName}ShowOrmAction')\n\n`
88+
routeString += `await route.get('${tableName}/{id}', () => 'Actions/${modelName}ShowOrmAction')\n\n`
6589

6690
if (apiRoute === 'destroy')
67-
routeString += `await route.delete('${modelNameFormatted}/{id}', () => 'Actions/${modelName}DestroyOrmAction')\n\n`
91+
routeString += `await route.delete('${tableName}/{id}', () => 'Actions/${modelName}DestroyOrmAction')\n\n`
6892

6993
return routeString
7094
}
7195

7296
async function initiateModelGeneration(): Promise<void> {
97+
7398
await deleteExistingModels()
99+
await deleteExistingOrmActions()
100+
74101
const modelFiles = glob.sync(path.userModelsPath('*.ts'))
75102

76103
for (const modelFile of modelFiles) {
@@ -79,7 +106,8 @@ async function initiateModelGeneration(): Promise<void> {
79106
const tableName = model.default.table
80107
const modelName = model.default.name
81108

82-
generateApiRoutes(model)
109+
await generateApiRoutes(model)
110+
83111

84112
const file = Bun.file(
85113
path.projectStoragePath(`framework/orm/${modelName}.ts`),
@@ -156,6 +184,14 @@ async function deleteExistingModels() {
156184
if (fs.existsSync(typePath)) await Bun.$`rm ${typePath}`
157185
}
158186

187+
async function deleteExistingOrmActions() {
188+
const ormPaths = glob.sync(path.projectStoragePath(`framework/orm/Actions/*.ts`))
189+
190+
for (const ormPath of ormPaths) {
191+
if (fs.existsSync(ormPath)) await Bun.$`rm ${ormPath}`
192+
}
193+
}
194+
159195
async function setKyselyTypes() {
160196
let text = ``
161197
const modelFiles = glob.sync(path.userModelsPath('*.ts'))

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

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -267,15 +267,16 @@ export class Router implements RouterInterface {
267267
callback: Route['callback'],
268268
): Promise<Route['callback']> {
269269
if (callback instanceof Promise) {
270+
270271
const actionModule = await callback
271272
return actionModule.default
272273
}
273274

274275
if (typeof callback === 'string')
275-
return this.importCallbackFromPath(callback, this.path)
276+
return await this.importCallbackFromPath(callback, this.path)
276277

277278
// in this case, the callback ends up being a function
278-
return callback
279+
return await callback
279280
}
280281

281282
private async importCallbackFromPath(
@@ -309,7 +310,7 @@ export class Router implements RouterInterface {
309310
const newPath = actionModule.default.path ?? originalPath
310311
this.updatePathIfNeeded(newPath, originalPath)
311312

312-
return actionModule.default.handle
313+
return await actionModule.default.handle()
313314
}
314315

315316
private normalizePath(path: string): string {

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

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@ export async function serve(options: ServeOptions = {}) {
2727
port,
2828
development,
2929

30-
fetch(req: Request) {
31-
return serverResponse(req)
30+
async fetch(req: Request) {
31+
return await serverResponse(req)
3232
},
3333
})
3434
}
@@ -70,7 +70,7 @@ export async function serverResponse(req: Request) {
7070
addRouteParamsAndQuery(url, foundRoute)
7171
executeMiddleware(foundRoute)
7272

73-
return execute(foundRoute, req, { statusCode: foundRoute?.statusCode })
73+
return await execute(foundRoute, req, { statusCode: foundRoute?.statusCode })
7474
}
7575

7676
function addRouteParamsAndQuery(url: URL, route: Route): void {
@@ -109,14 +109,14 @@ interface Options {
109109
statusCode?: StatusCode
110110
}
111111

112-
function execute(route: Route, request: Request, { statusCode }: Options) {
112+
async function execute(route: Route, request: Request, { statusCode }: Options) {
113113
if (!statusCode) statusCode = 200
114114

115115
if (route?.method === 'GET' && (statusCode === 301 || statusCode === 302)) {
116116
const callback = String(route.callback)
117117
const response = Response.redirect(callback, statusCode)
118118

119-
return noCache(response)
119+
return await noCache(response)
120120
}
121121

122122
if (route?.method !== request.method)
@@ -127,26 +127,26 @@ function execute(route: Route, request: Request, { statusCode }: Options) {
127127
try {
128128
const fileContent = Bun.file(route.callback)
129129

130-
return new Response(fileContent, {
130+
return await new Response(fileContent, {
131131
headers: { 'Content-Type': 'text/html' },
132132
})
133133
} catch (error) {
134-
return new Response('Error reading the HTML file', { status: 500 })
134+
return await new Response('Error reading the HTML file', { status: 500 })
135135
}
136136
}
137137

138-
if (isString(route.callback)) return new Response(route.callback)
138+
if (isString(route.callback)) return await new Response(route.callback)
139139

140140
if (isFunction(route.callback)) {
141141
const result = route.callback()
142-
return new Response(JSON.stringify(result))
142+
return await new Response(JSON.stringify(result))
143143
}
144144

145145
if (isObject(route.callback))
146-
return new Response(JSON.stringify(route.callback))
146+
return await new Response(JSON.stringify(route.callback))
147147

148148
// If no known type matched, return a generic error.
149-
return new Response('Unknown callback type.', { status: 500 })
149+
return await new Response('Unknown callback type.', { status: 500 })
150150
}
151151

152152
function noCache(response: Response) {

0 commit comments

Comments
 (0)