Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Appolo is an light web server MVC Framework for Node.js written in Typescript
Appolo architecture follows common patten of MVC and dependency injection which makes it easy to build better performance, flexibility and easy maintenance server side in nodejs.
npm install appolo --save
appolo
requires TypeScript compiler version > 2.1 and the following settings in tsconfig.json
:
{
"experimentalDecorators": true
}
In your app.js file:
var {createApp} from 'appolo';
createApp().launch();
node benchmarks/benchmarks
Machine: 2.2 GHz Intel Core i7, 16GiB RAM
Method: autocannon -c 100 -d 10 -p 10 localhost:3000
Name | Average | Min | Max |
---|---|---|---|
Req/Sec | 32,821.6 | 23,840 | 34,463 |
Appolo will require all files in the config
and src
folders, but the env
folder will be loaded first. All other folders are optional
|- config
|- env
|- all.ts
|- development.ts
|- production.ts
|- middlewares
|- all.ts
|- modules
|- logger.ts
|- src
|- controllers
|- managers
|- services
|- bootstrap.ts
|- app.ts
appolo launch configuration options, all options are optional
key | Description | Type | Default |
---|---|---|---|
paths | folders that will be required and loaded on appolo launch | array | [ 'src'] |
environment | environment file name that will override the settings in environments/all.js | string | `(process.env.NODE_ENV |
startMessage | the message that will be written to console log the the server starts | string | 'Appolo Server listening on port: {port} version:{version} environment: {environment}' |
startServer | if true the server will start immediately to listen to port else you will have to start in manually. | boolean | true |
port | the port that the app will listen to. | number | `process.env.PORT |
errorMessage | print route http error.toString() | boolen | true |
maxRouteCache | the max size of route lookup lru cache | number | 10000 |
import {createApp} from 'appolo';
(async ()=>{
let app = await createApp({
paths:[ 'src'],
root : process.cwd()+'/app',
environment : 'testing',
port:8182
}).launch();
})();
With environments you can define different configurations depending on the environment type your app is currently running.
It is recommended to have 4 types of environments: development
, testing
, staging
, production
.
After appolo.launch
you can always access the current environment vars via appolo.environment
.
//all.ts
export = {
name:'all',
someVar:'someVar'
}
//development.ts
export = {
name:'develpment',
db:'mongo://development-url'
}
//development.ts
export = {
name:'testing',
db:'mongo://testing-url'
}
If we launch our app.js with NODE_ENV = testing
import {createApp} from 'appolo';
...
let app = await createApp().launch();
var env = appolo.env;
console.log(env.name,env.someVar,env.db) // 'testing someVar monog:://testing-url'
You can configure express modules or add custom middleware by adding configuration files to the express folder.
The express configuration file is called after the environment files were loaded.
//middlewares/all.ts
import favicon = require('static-favicon');
import bodyParser = require("body-parser");
import {App,IRequest,IResponse,NextFn} from 'appolo';
export = function (app: App) {
app.use(bodyParser.json());
app.use(function (req:IRequest, res: IResponse, next: NextFn) {
res.setHeader("Access-Control-Allow-Origin", "*");
next();
});
app.use(favicon());}
You can easily bind a route path to a controller method.
The routes path are defined in the same way as in expressjs router.
Each route class has the following methods:
path
- same as in expressjs.method
- one of get
,post
,patch
,delete
,put
. default get
.action
- the action function the will be invoked to handle the route.middleware
- middleware function the will be invoked before the controller. If the next
function is not called or called with an error, the controller won`t be created.import {define,inject,Controller,IRequest,IResponse,get,post} from 'appolo';
@define()
export class TestController extends Controller{
@inject() dataManager:DataManager
@get("/test/:userId")
public test (req:IRequest, res:IResponse){
return this.dataManager.getData(req.params.userId));
}
}
or you can return response by using res.send
@define()
export class Test2Controller extends Controller{
@inject() dataManager:DataManager
@post("/test2/:userId")
public test (req:IRequest, res:IResponse) {
res.send(this.dataManager.getData(req.params.userId));
}
}
You can also define routes using appolo.route
method:
import {controller,inject,Controller,IRequest,IResponse} from 'appolo';
@controller()
export class TestController extends Controller{
@inject() dataManager:DataManager
public test (req:IRequest, res:IResponse) {
res.send(this.dataManager.getData());
}
}
app.route<TestController>(TestController)
.path("/test/")
.method(appolo.Methods.GET)
.action(c=>c.test)
Controllers are classes that handle routes request.
In order for the router to be able to handle the request, a controller class must extend Controller
.
Each controller action will be called with request and response objects.
import {controller,model,inject,Controller,IRequest,IResponse} from 'appolo';
@controller()
export class LoginController extends Controller{
@inject() authManager:AuthManager;
@post("/login/")
public async loginUser(req:IRequest,res:IResponse,@model() model:any){
return await this.authManager.validateUser(model.username,model.password)
}
}
By default, appolo creates a new controller instance for every request. If you do not need a new controller instance for every request, you can inherit from StaticController which is singleton.
import {controller,singleton,inject,lazy,mehtod,path,StaticController,Methods,IRequest,IResponse,IRouteOptions} from 'appolo';
@controller()
@singleton()
@lazy()
export class LoginController extends StaticController{
@inject() authManager:AuthManager;
@post("/login/")
public aynsc loginUser(req:IRequest,res:IResponse,@moel() model:any){
return await this.authManager.validateUser(req.model.username,req.model.password)
}
}
by default the response will be wrapped with try catch and InternalServerError
will be send to response.
{ status: 500, message: "Bad Request", error: "Internal Server Error" }
or you can throw custom error
import {controller,inject,Controller,IRequest,IResponse} from 'appolo';
@controller()
export class LoginController extends Controller{
@inject() authManager:AuthManager;
@post("/login/")
public async loginUser(req:IRequest,res:IResponse,@model() model:any){
try{
return await this.authManager.validateUser(model.username,model.password)
}catch(e){
throw new HttpError(401,"Not Found",e,{key:"value"},1000)
}
}
}
{
"status": 401, "message": "Not Foundr", "error":"something is wrong", "code":1001,key:"value"
}
A middleware class will run before the action of the controller is invoked.
The middleware class must extend must extend appolo.Middleware
and implement the run
method.
Middleware file:
import {define,inject,Middleware,IRequest,IResponse,NextFn,IRouteOptions} from 'appolo';
@define()
export class AuthMiddleware extends Middleware {
@inject() authManager:AuthManager;
public async run(req:appolo.IRequest,res:IResponse,next:NextFn,route:IRouteOptions){
try{
let user = await this.authManager.validateToken(req.headers.authorization)
req.user = user;
next();
}catch(e){
this.sendUnauthorized();
}
}
}
now you can added the middleware to our route
@controller()
export class LoginController extends Controller{
@post("/someroute/")
@middaleware(AuthMiddleware)
public async someAction(req:IRequest,res:IResponse){
return req.user
}
}
Appolo has a powerful Dependency Injection system based on appolo-inject.
It enables you to write organised, testable code based on the loose coupling idea.
You can always access the injector via app.injector
.
define
- make the object injectablesingleton
- the class will be created only once and the injector will return the same instance every timelazy
- wait for the class to be injected before creating italias
- add alias name to the object (allows injecting multiple objects which share an alias using injectAlias
)aliasFactory
- add alias factory name to the object (allows injecting multiple objects which share an alias using injectAliasFactory
)initMethod
- The method will be called after all instances were created and all the properties injected.inject
- inject instance reference by idinjectFactoryMethod
- factory method is a function that will return the injected object. This is useful to create many instances of the same class.injectAlias
- inject objects by alias nameinjectArray
- inject array of properties by reference or by valueinjectDictionary
- inject a dictionary of properties by reference or by value.injectAliasFactory
- inject factory methods by alias nameinjectFactory
inject object by factory classinjectObjectProperty
inject property of another objectinjectValue
inject property by valueinjectParam
- inject object by parameter//dataRemoteManager.ts
import {define,singleton,initMethod,inject,IFactory,factory} from 'appolo';
@define()
@singleton()
export class DataRemoteManager {
getData(){ ...}
}
//dataManager.ts
@define()
@singleton()
@factory()
export class DataManager implement IFactory {
@inject() dataRemoteManager:DataRemoteManager
get(){
return this.dataRemoteManager;
}
}
//fooController.ts
@controller()
export class FooController{
@inject() dataManager:DataManager
constructor() {
this.data = null
}
@initMethod()
initialize(){
this.data = this.dataManager.getData();
}
@get("/data")
getData(){
return this.data;
}
}
You can also use constructor injection or method parameter injection:
import {define,singleton,injectParam,initMethod,inject} from 'appolo';
@define()
@singleton()
export class DataManager {
getData(){ ... }
}
@define()
class FooController{
constructor(@injectParam() dataManager:DataManager) {
this.dataManager = dataManager;
}
@initMethod()
public initialize(){
this.data = this.dataManager.getData();
}
public test(@injectParam() logger:Logger){... }
}
Inherited injections are supported as well.
Anything you inject on a base class will be available to child classes.
Remember not to use @define
on the parent class.
import {define,singleton,injectParam,initMethod,inject} from 'appolo';
export class BaseManager {
@inject() protected env:any
private getData(){...}
}
@define()
class FooManager extends BaseManager{
@initMethod()
public initialize(){
//the env object in injected from the base class
console.log(this.env.test)
}
}
Appolo has a built-in event dispatcher to enable classes to listen to and fire events.
Event Dispatcher has the following methods:
import {define,singleton,injectParam,initMethod,inject,EventDispatcher} from 'appolo';
@define()
@singleton()
export class FooManager extends EventDispatcher{
public notifyUsers(){
this.fireEvent('someEventName',{someData:'someData'})
}
}
@define()
export class FooController {
@inject() fooManager:FooManager;
@initMethod()
public initialize(){
this.fooManager.on('someEventName',(data)=>{
this.doSomething(data.someData)
},this);
}
doSomething(data){...}
}
Third party modules can be easily loaded intto appolo inject and used in the inject container.
Each module must call appolo.module
before it can be used by appolo launcher
.
appolo.module
accepts a function as an argument. The last argument to that function must be the next
function: modules are loaded serially, so each module must call the next
function or return a promise
in order to continue the launch process.
Other arguments to the function are object which you wish to inject into the module (these objects must be injected earlier).
By default, each module can inject:
env
- environment object,inject
- injector - to add objects to the injector,Module example:
import {App} from 'appolo';
export = async function(app:App){
await app.module(async function(env:any,inject:appolo.Injector){
let myModuleObject = {data:'test'};
await toSomeThing();
inject.addObject('myModuleObject',myModuleObject);
});
}
Now we can inject myModuleObject
to any class:
import {define,singleton,initMethod,inject} from 'appolo';
@define()
export class AuthMiddleware{
@inject('myModuleObject') testObject:any
public doSomeThing() {
return this.testObject.data; //return 'test'
}
}
A logger module example with winston
loggerModule.js file:
import winston = require('winston');
import {App} from 'appolo';
export = async function(app:App){
await appolo.module(async function(env:any,inject:appolo.Injector){
transports = [];
transports.push(new (winston.transports.Console)({
json: false,
timestamp: true
})
});
let logger = new (winston.Logger)({ transports: transports});
inject.addObject('logger', logger);});
Now we you inject logger anywhere we need it:
import {define,singleton,initMethod,inject} from 'appolo';
@define()
export class DataManager{
@inject() logger:Logger
public initialize(){
this.logger.info("dataManager initialized",{someData:'someData'})
}
}
Once it launched, appolo will try to find an appolo bootstrap
class and call it's run
method. Only when the bootstrap is finished, the server will start
import {define,singleton,injectParam,initMethod,inject,bootstrap,IBootstrap} from 'appolo';
@define()
@bootstrap()
export class Bootstrap implements IBootstrap{
@inject() someManager1:SomeManager1
public async run(){
//start your application logic here
await this.someManager1.doSomeThing();
}
}
You can reset appolo sever by calling appolo.reset()
. This will clean all environments, config, injector and close the server.
grunt test
The appolo
library is released under the MIT license. So feel free to modify and distribute it as you wish.
FAQs
nodejs server framework
We found that appolo demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.