0.1.0-dev • Published 2 years ago

swiftter v0.1.0-dev

Weekly downloads
-
License
GPL
Repository
-
Last release
2 years ago

Swiftter

Quickly build and test powerful Express API's with built in route handling, authentication, middleware, deployment and testing so that you can focus on what is really important..

import Swiftter from 'swiftter';
const app = new Swiftter("Demo");
const logger = app.loggers.create("demo");

app.server.listen(300).then(p => {
    logger.info("Hello World!");
})

Installation

This is a Node.js module available through the npm registry.

Before installing, download and install Node.js. This package has been tested on Node.js 16.0 and higher.

Quick Start

Using the CLI

The quickest way to get started with express is to utilize the executable swiftter(1) to generate an application as shown below: Install the executable. The executable's major version will match Express's:

$ npm install -g swiftter-cli

Make and enter a folder:

$ mkdir swiftter-demo && cd swiftter-demo

Run the CLI to create the project

$ swiftter

Starting from scratch

Install swiftter as a dependancy

$ npm i swiftter

Import and initialize Swiftter

Before you can use some of Swiftter's fancy features, you first have to import and create an app

  1. Import swiftter into your project

    import Swiftter from 'swiftter';

  2. Create an instance of Swiftter Swiftter() has a constructor of name, being a string with the name of the app

    new Swiftter("swiftter-demo"); Returns new Swiftter

  3. (Optional) We will also need the built in path package to parse our route path

    import path from 'path';

import Swiftter from 'swiftter'; // import `swiftter`
import path from 'path'; // Import `path`

const app = new Swiftter("swiftter-demo"); // Create an instance of Swiftter

Initializing a server

Before we can use Swiftter, we need to initialize the express server ? == not required 1. Create an InitializeOptions variable

> * `routes?`: *(path.ParsedPath)* Folder location of your dynamic route files
> * `middleware?`: *(() => (req, res, next))[]*  Any extra middleware you want to include
> * `authentication?`: *Authentication[]* Authentication classes you want to use (see below)
> * `express`
>   * `session`: *(false | SessionOptions?)* Set to false to disable
>       * `secret`: *(string)* A secret to use for cookies
>   * `useCors`: *(boolean)* Use cors() in the application
>   * `useBodyParser`: *(false | BodyParserOptions?)* Set to false to disable
>       * `json?`: *(boolean)* Use bodyParser.json();
>       * `urlencoded?`: *(false | URLEncodedOptions)* Set to false to disable || Use bodyParser.urlencoded(); 
>           * `extended`: *(boolean)* Use extended mode
  1. Initialize app.server Swiftter#server#initialize() takes an InitializeOptions argument

    app.server.initialize(serverOptions) Returns void

  2. Listen on a port Swiftter#server#listen() takes a number argument being the port

    app.server.listen(3000); Returns Promise<number>

import Swiftter from 'swiftter';
import path from 'path';

const app = new Swiftter("swiftter-demo");

const serverOptions: InitializeOptions = { // We creating an InitializeOptions variable
    routes: path.parse(path.join(process.cwd(), "dist", "routes")),
    middleware: [],
    authentication: [],
    express: {
        session: {
            secret: "SECRET :)"
        },
        useCors: false,
        useBodyParser: false
    }
}

app.server.initialize(serverOptions); // We are initializing the app with the above options
await app.server.listen(3000); // We are listening on port 3000

Using Loggers

We can create loggers to log to the output in a fancy way

  • Creating a logger Swiftter#loggers#create() takes a string argument being the logger name

    app.loggers.create("Main") Returns Logger

  • Fetching a logger Swiftter#loggers#cache is a Map<string (name), Logger> of all the fetched/registered loggers Using Swiftter#loggers#get() we can fetch a logger we have already created, instead of exporting it.

    app.loggers.cache.get("Main") Returns Logger

  • Using a logger All methods on a Logger can take a string, string[] or MessageGroup argument. These methods include;
    • #info() Returns void
    • #warn() Returns void
    • #error() Returns void
    • #success() Returns void
    • #debug() Only logs if process.env.NODE_ENV === "development" Returns void
import Swiftter from 'swiftter';
import path from 'path';

const app = new Swiftter("swiftter-demo");
const logger = app.loggers.create("Main"); // We create a logger

const serverOptions: InitializeOptions = {
    routes: path.parse(path.join(process.cwd(), "dist", "routes")),
    middleware: [],
    authentication: [],
    express: {
        session: {
            secret: "SECRET :)"
        },
        useCors: false,
        useBodyParser: false
    }
}

app.server.initialize(serverOptions);
app.server.listen(3000).then(p => { // We are now using .then() to collect the port
    logger.success([`Listening on port:`, p]); // And logging it out using Logger#success()
});

Creating a Route

Using the built in dynamic route features, we can simply create files in a directory to create advanced routes 1. Move into your InitializeOptions#routes directory and create an index.ts By default, this will be your / route 2. For TypeScript, import { Route } from swiftter This will give you the config layout for routes import { Route } from 'swiftter' 3. Create a new variable with the above Route as the type const route: Route = {} Adding the type is optional 4. Add a method property, being (get|post|patch|delete|put) to set the method of the route method: "get" 5. Add a handler property, being a (req, res) => void function to handle the route handler(req, res) => {}

  • Optional: Add a path property to set the web path of the route, this will disable dynamic routing for the file path: "/hello"
  1. Export the Object It is important to make sure you export default the route object export default route; With route being the variable name
import { Route } from 'swiftter'; // We are importing the route type

const route: Route = {
    method: 'get', /* The method of the route, can be "get", "post", "put", "patch", or "delete" */
    // path: '/optional', /* The "path" paramater is optional, it defaults to using dynamic routing */
  
    handler: (req, res) => { /* A handler function, taking "req" and "res" as arguments */
        res.send(`Hello World`)
    },
};

export default route; /* Export the route object */

Using Authentication

Swiftter has built in authentication, to make it easy to encorperate simple or even complex authentication stratergies

Discord Authentication

  1. Import { Scope, DiscordAuthentication } from 'swiftter'

    import { Scope, DiscordAuthentication } from 'swiftter';

  2. Create a DiscordAuthenticationOptions variable
    • clientID: (string) Your discord application's client id
    • clientSecret: (string) Your discord application's client secret
    • callbackURL: (string) A callback url you added to your discord application's oAuth settings. Make sure it calls back to this app
    • scopes: (Scope[]) A list of scopes from the scope enum
    • urls
      • successUrl: (string) Url to redirect to after successful login. Defaults to /
      • callback: (string) The path to your callbackURL. Defaults to /auth/callback/discord
      • authorization: (string) Url a user needs to go to to authenticate. Defaults to /auth/discord
      • failureRedirect: (string) Url a user is redirected to if the redirect fails. Defaults to /
    • storage
      • methods: (string)