hsscaffold
v1.0.2
Published
Custom managed MVC scaffolding for Fastify
Readme
hsscaffold
Custom managed MVC scaffolding for Fastify.
This is the little MVC framework I keep reaching for on my own Fastify projects, pulled out into a package so I stop copy-pasting it everywhere. If you've ever written an ASP.NET MVC app it'll feel familiar, you write controllers with action methods, decorate them, and routing/sessions/auth/views are handled for you. It's what I like.
As a warning, It's built around the way I lay things out, views live in views/, static files in wwwroot/, and there's exactly one scaffold per process. None of that is configurable, and that's the point.
What you get
- An ASP.NET-ish builder (
ScaffoldBuilder) to wire stuff up. - Controllers driven by decorators:
@Get,@Post,@Put,@Route,@Auth,@AllowAnonymous,@RateLimit. - Routing worked out from your controller and action names so you rarely write a path by hand.
- In-memory sessions tracking.
- Role/claim based auth, checked per-action or for a whole controller.
- The usual action result helpers, e.g.
view,redirect,redirectToAction,ok,badRequest,unauthorised,forbidden,notFound, which you'll be used to if you've ever used ASP.NET before. - EJS, static files, cookies, form bodies, and rate limiting all registered for you.
Getting started
npm install hsscaffoldEverything is exported from the package root:
import { ScaffoldBuilder, Controller, Get, Post, Put, Route, Auth, AllowAnonymous, RateLimit, Session, SessionUser, HeadersTemplate, ClaimType } from "hsscaffold";The controllers lean on decorators, so you'll need "experimentalDecorators": true in your tsconfig.json.
A tiny app looks like this:
import { ScaffoldBuilder, Controller, Get, Post, AllowAnonymous } from "hsscaffold";
class HomeController extends Controller {
@Get
@AllowAnonymous
public async Index() {
// Renders views/home/index.ejs
const indexViewModel: IndexViewModel = {
data: await UserService.LoadUser(this.session.GetClaim(ClaimType.Identity))
}
return this.view(indexViewModel);
}
// Route requires auth because of missing @AllowAnonymous
@Get
public About() {
return this.view();
}
}
const fastify = new ScaffoldBuilder()
.SetLogger(true)
.SetSessionConfig({
validity: 86400000, // how long a session lives in ms (e.g. a day)
length: 64, // session id length in bytes
secret: process.env.SECRET, // please please please set your own, don't ship the default
cookieName: "MY_APP_SESSION", // optional, defaults to HS_SCAFFOLD_SESSION
})
.RegisterController(HomeController)
.Build();
fastify.listen({ port: 3000 });Views and static files are looked up relative to wherever you run the app from, so the layout it expects is:
your-app/
├─ views/ # EJS templates, one folder per controller
│ ├─ home/
│ │ ├─ index.ejs
│ │ └─ about.ejs
│ └─ 404.ejs # shown when nothing matches
├─ wwwroot # served as static files at /
└─ controllers
└─ ...your controllersHow routing works
Controller name (minus the Controller suffix) plus the action method name gives you the path, and the decorator decides the verb. Most of the time you don't write a route at all.
| Controller | Action | Method | Where it lands |
| ----------------- | --------- |--------| ------------------------------- |
| HomeController | Index | @Get | /, /home, /home/index |
| HomeController | About | @Get | /about, /home/about |
| UsersController | Index | @Get | /users, /users/index |
| UsersController | Profile | @Get | /users/profile |
A couple of conventions worth knowing: Home/Index is treated as the root of the site, so its actions also mount at /. And an index action mounts at the controller root as well as its own path.
When the convention doesn't fit, use @Route to force a path like this:
class UsersController extends Controller {
@Get
@Route("/u")
public Profile() {
return this.view();
}
}Inside an action
this inside an action is the request context — it's got the request, the response, the session, and all the result helpers hanging off it:
class AccountController extends Controller {
@Get
@AllowAnonymous
Login() {
return this.view();
}
@Post
@AllowAnonymous
Login(body: { username: string; password: string }) {
if (!body.username) {
return this.badRequest("Username is required");
}
// ...check the password...
return this.redirectToAction("index", "home");
}
}Every view model quietly gets session added to it, along with anything you've registered through RequestCtx.Inject(key, value), which is handy for stuff you want in every template.
Form fields with indexed names like items[0].name get turned back into arrays of objects automatically, like ASP.NET.
Sessions and auth
Hand a session out with Session.AssignUserSession(res). That sets the session cookie (named HS_SCAFFOLD_SESSION unless you renamed it with cookieName in SetSessionConfig) and gives you back a SessionUser to pile claims onto:
import { Session, ClaimType } from "hsscaffold";
const session = Session.AssignUserSession(this.res);
session.AddClaim(ClaimType.Identity, userId);
session.AddClaim(ClaimType.Name, "Holly");
session.AddClaim(ClaimType.Role, "Admin");By default everything needs a session — no cookie, and the request gets bounced to /account/login?returnTo=.... Mark the public bits with @AllowAnonymous.
To gate something on a role, use @Auth. It works on a single action or on the whole controller:
class AdminController extends Controller {
@Get
@Auth("admin")
Dashboard() {
return this.view();
}
}
// ...or lock down the whole thing:
@Auth("admin")
class AdminController extends Controller { /* ... */ }Expired sessions get cleaned up on an hourly sweep, so you don't have to think about it. Session.Clear(cookies, res) logs someone out, and Session.CheckValiditiy(cookies) looks up whoever's currently signed in.
The claim types are just an enum:
enum ClaimType { Identity, Name, EmailAddress, Role }The builder
new ScaffoldBuilder() is chainable, call what you need and finish with .Build():
| Method | What it does |
| ------ |-------------------------------------------------------------------------------------------------|
| SetLogger(state) | Turn Fastify's logger on or off. |
| SetSessionConfig(config) | Configures session values, see interfaces/SessionConfig.ts for more details. |
| RegisterController(controller) | Adds a controller to be registered on .Build() |
| Register(plugin, options?) | Drop in any Fastify plugin before startup. |
| SetHeadersTemplate(template) | Apply a shared set of response headers (see below). |
| Register404Handler(handler) | Replace the default not-found handler. |
| Build() | Puts it all together and hands back the FastifyInstance, as if you'd constructed it yourself. |
Rate limiting a route
class AccountController extends Controller {
@Post
@AllowAnonymous
@RateLimit({ max: 5, timeWindow: 60000 }) // five requests per minute
Login() { /* ... */ }
}Shared headers
If you want the same headers on every response (e.g. security headers), use a HeadersTemplate:
import { HeadersTemplate } from "hsscaffold";
const headers = new HeadersTemplate();
headers.AddHeader("X-Frame-Options", "DENY");
headers.AddHeader("Content-Security-Policy", "default-src 'self'");
new ScaffoldBuilder()
.SetHeadersTemplate(headers)
// ...
.Build();