swiftter v0.1.0-dev
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
- Import swiftter into your project
import Swiftter from 'swiftter';
- Create an instance of Swiftter
Swiftter()
has a constructor of name, being a string with the name of the appnew Swiftter("swiftter-demo");
Returnsnew Swiftter
- (Optional) We will also need the built in
path
package to parse our route pathimport 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
Initialize
app.server
Swiftter#server#initialize()
takes anInitializeOptions
argumentapp.server.initialize(serverOptions)
Returnsvoid
Listen on a port
Swiftter#server#listen()
takes anumber
argument being the portapp.server.listen(3000)
; ReturnsPromise<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 astring
argument being the logger nameapp.loggers.create("Main")
ReturnsLogger
- Fetching a logger
Swiftter#loggers#cache
is aMap<string (name), Logger>
of all the fetched/registered loggers UsingSwiftter#loggers#get()
we can fetch a logger we have already created, instead of exporting it.app.loggers.cache.get("Main")
ReturnsLogger
- Using a logger
All methods on a
Logger
can take astring
,string[]
orMessageGroup
argument. These methods include;#info()
Returnsvoid
#warn()
Returnsvoid
#error()
Returnsvoid
#success()
Returnsvoid
#debug()
Only logs ifprocess.env.NODE_ENV === "development"
Returnsvoid
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 filepath: "/hello"
- Export the Object
It is important to make sure you
export default
the route objectexport default route;
Withroute
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
- Import
{ Scope, DiscordAuthentication }
from 'swiftter'import { Scope, DiscordAuthentication } from 'swiftter';
- Create a
DiscordAuthenticationOptions
variableclientID
: (string) Your discord application's client idclientSecret
: (string) Your discord application's client secretcallbackURL
: (string) A callback url you added to your discord application's oAuth settings. Make sure it calls back to this appscopes
: (Scope[]) A list of scopes from thescope
enumurls
successUrl
: (string) Url to redirect to after successful login. Defaults to/
callback
: (string) The path to yourcallbackURL
. 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)