This is my simple experiment with Deno and Typescript. I made a simple framework, in which there are routes, controllers and views. This is just for studying.
- Make sure you have Deno installed on your machine
- Clone this repo
- Run:
cd deno-simple-framework
- Run:
deno run --allow-net --allow-read main.ts
- Open
http://localhost:8000
in your browser - Done
The way this framework works is simple:
- The main.js file will run
- In the file there is an HTTP server built on top of the
serve
module (_bootstrap.ts, _server.ts) - The app will start the routing system (_routing.ts)
- The routing system will read the
app/routes.ts
file - When the user makes a request, the routing system will read the request and look for a match route in the
app/routes.ts
file - Then the matching route will be used
- Each route has a controller
- The controller will be used to handle user requests
- Each controller has a
contentType
property and also therender
method - The
contentType
property is used for HTTP header responses, whilerender
is used as HTTP body - The server will return an HTTP response
There are currently 3 routes:
- / (index page)
- /about (about page)
- Json (return JSON)
// controllers
import IndexController from './controllers/IndexController.ts';
import AboutController from './controllers/AboutController.ts';
import JsonController from './controllers/JsonController.ts';
// local module
import { Route, Routes } from './../_routing.ts';
export const routes: Routes = {
'/': {
controller: IndexController
},
'/about': {
controller: AboutController
},
'/json': {
controller: JsonController
},
// your own route here
}
Each route requires a controller.
This controller will return the HTML string. If your controller has a text/html
content type, then you don't need to declare it again, because that's the default.
import { BaseController } from './../../_base_controller.ts';
export default class IndexController extends BaseController {
render(): string {
return `<p>Hello</p>`;
}
}
This controller will return the name of the view file. The file used by this controller is in app/views/*
. The routing system will automatically take the contents of the view file and use it as an HTTP body.
import { BaseController } from './../../_base_controller.ts';
export default class AboutController extends BaseController {
render(): string {
return `views.about`;
}
}
This controller will return JSON. The routing system uses JSON.stringify
before the object is used as an HTTP body.
import { BaseController } from './../../_base_controller.ts';
export default class JsonController extends BaseController {
contentType = 'application/json';
render(): object {
return {
user: 'Nauval'
};
}
}