MVC web server framework for Deno 🦕 built on Oak

Related tags

Documentation Knight
Overview

Knight

A MVC REST framework for Deno 🦕 built on Oak. Generate Controller-based CRUD APIs with ease.

GitHub Workflow Status All Contributors GitHub release Deno

About

This framework allows you to create a rich REST API with just a few lines of code. The web server is powered by Oak and utilizes Deno’s native HTTP server and builds upon the existing middleware and routing stack, to allow for automatic endpoint generation.

Focus on what you want to do, and the framework will take care of the rest.

Documentation

View the full technical documentation.

Getting Started

You can use the knight framework in three different ways, start by importing the latest version of the Knight module. Now either let Knight create a new server instance, or use an existing Oak application. In the example below we will use the former.

/index.ts

import { Knight } from "https://deno.land/x/knight/mod.ts";
import UserController from "./controller/UserController.ts";

const app = Knight.createApi([
  new UserController(),
]);

console.log("Server ready on http://localhost:8000");

await app.listen({ port: 8000 });

In this introduction, we will use the UserController class from the example above.

Project Structure

We suggest that the project structure is as follows:

/
├── controller/
│   └── UserController.ts
├── model/
│   └── User.ts
├── index.ts

Now let's create the UserController class. By default the framework provides a IController class, which is a base class for all controllers and provides a set of overloadable methods that are common to all controllers. Such methods include get, getById, post, delete and put. Though you can easily define your own custom endpoints using the @Endpoint decorator.

/controller/UserController.ts

import {
  bodyMappingJSON,
  Context,
  Controller,
  created,
  Endpoint,
  IController,
  ok,
  Params,
} from "https://deno.land/x/knight/mod.ts";

import User from "../model/User.ts";

@Controller("/user")
export default class UserController extends IController {
  async post({ request, response }: Context): Promise<void> {
    const user = await bodyMappingJSON(request, User);
    created(response, `User ${user.firstName} was successfully created`);
  }

  @Endpoint("GET", "/:id/email")
  getByEmail({ id }: Params, { response }: Context): void {
    const email = id + "@example.com";
    ok(response, `User with email ${email} was successfully found`);
  }
}

The controller class is responsible for handling all requests to the endpoint. Knight comes with a set of built-in mapping functions that can be used to handle request of different DTO classes. One of these functions is bodyMappingJSON. This function takes a request and a class and returns the parsed body as an instance of the class. In the example above, the request body is parsed as a JSON object and returned as an instance of the User class.

Creating a model class is as easy as defining a regular class. Mark nullable, or optional properties with the ? symbol and the @Optional decorator to signify that the property is optional to body mapping functions.

/model/User.ts

import { Optional } from "../../mod.ts";

export default class User {
  firstName: string;
  lastName: string;
  email: string;
  @Optional()
  country: string;
  @Optional()
  city?: string;
  @Optional()
  phone?: number;

  constructor(
    firstName: string,
    lastName: string,
    email: string,
    country: string,
    city?: string,
    phone?: number,
  ) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.email = email;
    this.country = country;
    this.city = city;
    this.phone = phone;
  }
}

View the source code for this example code on GitHub.

Endpoints

As described in the previous section, the framework provides a set of overloadable methods that are commonly used through the IController class. These methods are:

  • get(ctx: Context): void | Promise<void>
  • getById(id: string, ctx: Context): void | Promise<void>
  • post(ctx: Context): void | Promise<void>
  • delete(id: string, ctx: Context): void | Promise<void>
  • put(id: string, ctx: Context): void | Promise<void>

All of these methods are overloaded to accept a Context object, which is a type provided by Knight to allow for easy access to the request and response objects. As well as the Params object for custom @Endpoint methods, which contains the parameters passed to the endpoint.

All of these have full support for asynchronous alternatives, which means that you can use async/await and return a Promise from the controller method and the framework will adapt the response accordingly.

Contribute

All contributions are welcome! Create an issue or pull request on GitHub to help us improve the framework.

Contributors

Thanks goes to these wonderful people (emoji key):


William Rågstad

💻 🚇 ⚠️ 📖 🎨 💡 🤔 📦 🔌 🖋

This project follows the all-contributors specification. Contributions of any kind welcome!

You might also like...

We.js, extensible Node.js MVC framework - CLI

We.js ;) We.js is a extensible node.js MVC framework For information and documentation see: http://wejs.org This repository (wejs/we) have the We.js C

Nov 10, 2022

MVC framework making it easy to write realtime, collaborative applications that run in both Node.js and browsers

Derby The Derby MVC framework makes it easy to write realtime, collaborative applications that run in both Node.js and browsers. Derby includes a powe

Dec 31, 2022

We.js, extensible Node.js MVC framework - CLI

We.js ;) We.js is a extensible node.js MVC framework For information and documentation see: http://wejs.org This repository (wejs/we) have the We.js C

Nov 10, 2022

Realtime MVC Framework for Node.js

Realtime MVC Framework for Node.js

Website Get Started Docs News Submit Issue Sails.js is a web framework that makes it easy to build custom, enterprise-grade Node.js apps. It is design

Dec 31, 2022

MVC framework making it easy to write realtime, collaborative applications that run in both Node.js and browsers

Derby The Derby MVC framework makes it easy to write realtime, collaborative applications that run in both Node.js and browsers. Derby includes a powe

Dec 23, 2022

Crate a full-stack web framework built with deno!

crate crate is a fullstack web framework built on deno! available on: [deno.land/x] [github] get started all you need to do is make two files. serious

Nov 11, 2022

A focused RESTful server framework for Deno 🌰🦕

acorn Rapidly develop and iterate on RESTful APIs using a strongly typed router designed for Deno CLI and Deno Deploy. import { Router } from "https:/

Dec 10, 2022

A server side rendering framework for Deno CLI and Deploy. 🦟 🦕

nat A server side rendering framework for Deno CLI and Deploy. Incorporating acorn, nano-jsx, and twind, it provides the tooling to provide a server c

Nov 17, 2022

This is a simple boilerplate for a Deno website, deployed with Deno Deploy.

Simple Deno Website Boilerplate This is a simple website boilerplate built using Deno and deployed using Deno Deploy. Demo at simple-deno-website-boil

Dec 3, 2022

TypeSafe MongoDB Atlas Data API SDK for Deno & Deno Deploy

Atlas SDK atlas_sdk is a TypeSafe MongoDB Atlas Data API SDK for Deno & Deno Deploy Links Docs Import Replace LATEST_VERSION with current latest versi

Dec 26, 2022

Deno bindings for yoga, using Deno FFI.

deno_yoga Deno bindings for yoga, using Deno FFI. Usage flags: --allow-ffi: Requires ffi access to "yogacore.dll", "libyogacore.so", "libyogacore.dyli

Feb 11, 2022

🛣️ A tiny and fast http request router designed for use with deno and deno deploy

Rutt Rutt is a tiny http router designed for use with deno and deno deploy. It is written in about 200 lines of code and is pretty fast, using an exte

Dec 10, 2022

deno-ja (Deno Japanese community) showcase

Showcase Deno本家よりも気軽に作ったものを公開できるようなShowcaseです。 スクリーンショットの撮影方法 短めのidを決めていただいて、下記のようにスクリプトを実行してください。 deno task screenshot [url] [id] ※エラーが出る場合は、下記を実行してみ

Oct 28, 2022

A command-line tool to manage Deno scripts installed via deno install

🏞️ nublar nublar is a command-line tool to manage your scripts installed via deno install. 🛳️ Installation deno install --allow-read --allow-write -

Dec 26, 2022

A fast and optimized middleware server with an absurdly small amount of code (300 lines) built on top of Deno's native HTTP APIs

A fast and optimized middleware server with an absurdly small amount of code (300 lines) built on top of Deno's native HTTP APIs with no dependencies. It also has a collection of useful middlewares: log file, serve static, CORS, session, rate limit, token, body parsers, redirect, proxy and handle upload. In "README" there are examples of all the resources. Faster's ideology is: all you need is an optimized middleware manager, all other functionality is middleware.

Dec 28, 2022

Monolithic repo for api server, image server, web server

Onsecondary Market Deployed at https://market.onsecondary.com Monolithic repo for api server, image server, web server TODO -use a script to cull expi

Jan 11, 2022

Lightweight MVC library for building JavaScript applications

Spine Spine is a lightweight MVC library for building JavaScript web applications. Spine gives you structure and then gets out of your way, allowing y

Jan 4, 2023

Super minimal MVC library

Espresso.js Espresso.js is a tiny MVC library inspired by Backbone and React with a focus on simplicity and speed. We've aimed to bring the ideas of u

Dec 11, 2022

Flipkart Clone using MERN Stack with proper File Structure and also follow MVC architecture. You can view live app.

Flipkart Clone using MERN Stack with proper File Structure and also follow MVC architecture.  You can view live app.

Flipkart Clone MERN APP Dhaval Patel's Flipkart Clone is done with top-notch features for the entrepreneur startups like Flipkart. It has strong authe

Dec 29, 2022
Comments
Releases(2.3.0)
  • 2.3.0(Mar 14, 2022)

    Complete overhaul of the logging system, refactored formatters and cleaned up sinks. Implemented an advanced templating system for logging messages and a default color printing of JSON objects. Added more tests for new logging system.

    Full Changelog: https://github.com/WilliamRagstad/Knight/compare/2.2.1...2.3.0

    Source code(tar.gz)
    Source code(zip)
  • 2.2.1(Mar 10, 2022)

    Custom endpoint handlers missing a this reference were fixed in the previous release, tho the built-in endpoints were still broken.

    Full Changelog: https://github.com/WilliamRagstad/Knight/compare/2.2.0...2.2.1

    Source code(tar.gz)
    Source code(zip)
  • 2.2.0(Mar 9, 2022)

    This release comes with lots of new features and a bunch of bug fixes! Easily create APIs with the latest introduction of static Service decorator.

    What's Changed

    • Implement Logging Support by @WilliamRagstad in https://github.com/WilliamRagstad/Knight/pull/4
    • Add Service Decorator by @WilliamRagstad in https://github.com/WilliamRagstad/Knight/pull/5

    Full Changelog: https://github.com/WilliamRagstad/Knight/compare/2.1.0...2.2.0

    Source code(tar.gz)
    Source code(zip)
  • 2.1.0-fix(Feb 25, 2022)

  • 2.1.0(Feb 25, 2022)

    Knight has gotten a brand new build system when creating web server APIs! No longer import all your controllers in index.ts, simply run

    const app = await Knight.build();
    

    And the framework will located all controllers under the current working directory for you! You don't need to change any other part of your code, just remove all imports and clean up your server code! 🎉🎆

    Source code(tar.gz)
    Source code(zip)
  • 2.0.4(Feb 25, 2022)

  • 2.0.3(Feb 10, 2022)

  • 2.0.0(Feb 8, 2022)

Owner
William Rågstad
Software Engineer, Full-Stack Developer & Computer Science Student @KTH building Awesome Open-Source Software and Programming Languages. Member of ACM SIGPLAN.
William Rågstad
Differences between Node + Koa and Deno + Oak

Node + Koa VS Deno + Oak Differences between Node + Koa and Deno + Oak About This is a project that aims to observe the differences between a simple R

Ronald Guilherme P. dos Santos 3 Jun 28, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Opinionated collection of TypeScript definitions and utilities for Deno and Deno Deploy. With complete types for Deno/NPM/TS config files, constructed from official JSON schemas.

Schemas Note: You can also import any type from the default module, ./mod.ts deno.json import { type DenoJson } from "https://deno.land/x/[email protected]

deno911 2 Oct 12, 2022
AngularJS SPA Template for Visual Studio is a project skeleton for a simple single-page web application (SPA) built with AngularJS, Bootstrap, and ASP.NET (MVC, Web Api, SignalR).

AngularJS SPA Template for Visual Studio This project is a skeleton for a simple single-page web application (SPA) built on top of the: AngularJS 1.2.

Kriasoft 105 Jun 18, 2022
Project implements decorators for oak like Nest.js.

oak decorators Project implements decorators like implementation of Nest.js for Deno's web framework oak. Usage The following are the core files that

akihiro tanaka 5 Dec 5, 2022
Component based MVC web framework for nodejs targeting good code structures & modularity.

Component based MVC web framework for nodejs targeting good code structures & modularity. Why fortjs Based on Fort architecture. MVC Framework and fol

Ujjwal Gupta 47 Sep 27, 2022
🦕 An example utilities bot using Deno with harmony as framework, hosted on Deno Deploy

Pekusara An example utilities bot using Deno with harmony as framework. Invite the production bot to your server. Invite Scripts Add the bot token to

Eliaz Bobadilla 6 Nov 12, 2022
A small, but powerful HTTP library for Deno & Deno Deploy, built for convenience and simplicity

Wren Wren is a small, but powerful HTTP library for Deno & Deno Deploy, built for convenience and simplicity. convenient aliases for HTTP responses au

Jakub Neander 69 Dec 12, 2022