Skip to content

Commit

Permalink
Merge pull request #4 from Potentii/v2.1.0
Browse files Browse the repository at this point in the history
v2.1.0
  • Loading branch information
Potentii authored Mar 15, 2017
2 parents 0bc5009 + d01420c commit 1f349a3
Show file tree
Hide file tree
Showing 10 changed files with 574 additions and 86 deletions.
92 changes: 92 additions & 0 deletions docs/configurator.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,39 @@ This will register a middleware for a `GET` request on `'/some-route'`.

<br>

### Configurator.HOOKS

_object_ \- A static enum of all the available hooks events names, which are _(in the order they're executed)_:

- `BEFORE_SETUP` \- It'll be emitted when the internal `Expressjs` instance is created, but before it gets configured
- `BEFORE_API_SETUP` \- It'll be emitted right before the `API` resources are set
- `AFTER_API_SETUP` \- It'll be emitted when all the `API` resources have been set
- `BEFORE_STATIC_SETUP` \- It'll be emitted right before the `static` resources are set
- `AFTER_STATIC_SETUP` \- It'll be emitted when all the `static` resources have been set
- `AFTER_SETUP` \- It'll be emitted when all the configurations were applied and the server is about to get initialized

_**Note:** All the hook functions will receive the `express instance`, and the `express module` as arguments._

_**Note:** You can also use the hook event name itself, they are: `'before-setup'`, `'before-api-setup'`, `'after-api-setup'`, `'before-static-setup'`, `'after-static-setup'` and `'after-setup'`._

#### Examples

Using with the [`Configurator.prototype.on(event, listener)`](#configuratorprototypeonevent-listener) to register hook functions:

```javascript
server
.on(Configurator.HOOKS.BEFORE_API_SETUP, (app, express) => {
// *Do something cool...
})
.on('before-api-setup', (app, express) => {
// *Do something cool here...
});
```

***

<br>

### Configurator.prototype.server\_port

_number|string_ \- The server port
Expand Down Expand Up @@ -85,6 +118,65 @@ server.port(process.env.PORT); // Will use the PORT environment variable

<br>

### Configurator.prototype.notFound(middleware)

Registers middlewares to handle 404 responses.

_**Note:** it can be used to send custom 404 pages or API responses._

_**Note:** you can call this method multiple times to add more middlewares, but you can also simply pass an array of middlewares._

#### Parameters

- `middleware` _function|function[]_ \- A valid Expressjs middleware function

#### Returns

[_Configurator_](#) \- This same configurator (for method chaining)

#### Examples

```javascript
server
.notFound((req, res, next) => {
// *Do something cool here...
});
```

***

<br>

### Configurator.prototype.on(event, listener)

Registers a handler for a given event.

_**Note:** it can be used to configure hook functions._

_**See:**_ [_`Configurator.HOOKS`_](#configuratorhooks) _for all the hooks events available._

#### Parameters

- `event` _string_ \- The event name
- `listener` _function_ \- The handler function

#### Returns

[_Configurator_](#) \- This same configurator (for method chaining)

#### Examples

```javascript
server
.on('before-api-setup', (app, express) => {
// *Do something cool here...
});
```

***

<br>

### Configurator.prototype.start()

Starts the server instance.
Expand Down
8 changes: 5 additions & 3 deletions docs/static-configurator.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,17 @@ _**Note:** readonly, use the_ [_`add()`_](#staticconfiguratorprototypeaddroute-r

## Methods

### StaticConfigurator.prototype.index(file)
### StaticConfigurator.prototype.index(file, options)

Sets the main HTML file

_**Note:** The given file will be served in the root route (<http://localhost/>)._
_**Note:** By default, the given file will be served only on the root route (i.e. <http://localhost/>)._

#### Parameters

- `file` _string_ \- The relative/absolute file path
- `options` _object_ \- \[optional\] Aditional options, the following properties can be set:
- `options.root_only` _boolean_ \- It sets whether the index file should be served only at the root route (`'/'`), or at all available routes (initial value is `true`)

#### Returns

Expand All @@ -61,7 +63,7 @@ _**Note:** The given file will be served in the root route (<http://localhost/>)

```javascript
server.static
.index('../src/my_index.html');
.index('../src/my_index.html', { root_only: true });
```

***
Expand Down
113 changes: 94 additions & 19 deletions libs/boot-server.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* The server instance
*/
let server;
let server = null;

/**
* A set of connection sockets
Expand Down Expand Up @@ -54,23 +54,40 @@ function stop(){
* @return {Promise} The server starting promise
* @author Guilherme Reginaldo Ruella
*/
function startServer({ server_port, index_file, static_resources, api_resources }){
function startServer({ server_port, not_found_middlewares, index, static_resources, api_resources, ee }){
// *Returning the starting promise:
return new Promise((resolve, reject) => {
// *Requiring the needed modules:
const headers_util = require('./http-headers-util.js');
const { PARSERS } = require('./parsers.js');
const { METHODS } = require('./methods.js');
const { HOOKS } = require('./hooks.js');
const express = require('express');
const body_parser = require('body-parser');
const url = require('url');

// *Preparing the Expressjs instance:
const app = express();


// *Emitting the 'before setup' event:
ee.emit(HOOKS.BEFORE_SETUP, app, express);


// *Trying to configure the server:
try{

// *Defining the prefixed middleware:
app.use((req, res, next) => {
// *Setting the default status code to 404:
res.status(404);
// *Sending to the next middleware:
next();
});

// *Emitting the 'before api setup' event:
ee.emit(HOOKS.BEFORE_API_SETUP, app, express);

// *Getting each dynamic resource:
for(let { methods, route, middleware, advanced } of api_resources){

Expand Down Expand Up @@ -211,34 +228,87 @@ function startServer({ server_port, index_file, static_resources, api_resources
}


// *Getting each static resource:
for(let { route, path } of static_resources){
// *Serving the static resource:
app.use(route, express.static(path));
}
// *Emitting the 'after api setup' event:
ee.emit(HOOKS.AFTER_API_SETUP, app, express);


// *Emitting the 'before static setup' event:
ee.emit(HOOKS.BEFORE_STATIC_SETUP, app, express);


// *Checking if there is any static resources set:
if(static_resources.length){
// *If there is:
// *Defining the static headers middleware:
const static_middleware = (res, path, stat) => res.status(200);

// *Getting each static resource:
for(let { route, path } of static_resources){
// *Serving the static resource:
app.use(route, express.static(path, {
index: false,
redirect: false,
setHeaders: static_middleware
}));
}
}

// *Checking if the index file is set:
if(index_file){
if(index && index.file){
// *If it is:
// *Serving the index file:
app.use('/', (req, res, next) => {
// *Sending the file:
res.status(200)
.sendFile(index_file);
});
// *Building the index page middleware:
let index_middleware = (req, res, next) => {
// *Sending the index file:
res.status(200).sendFile(index.file);
};

// *Checking if the 'roots only' flag is true:
if(index.options.root_only){
// *If it is:
// *Only sending the index poge on the root route:
app.get('/', index_middleware);
} else{
// *If it's not:
// *Sending the index page on all the available routes:
app.get('/*', index_middleware);
}
}


// *Handling 404 errors:
// *Emitting the 'after static setup' event:
ee.emit(HOOKS.AFTER_STATIC_SETUP, app, express);


// *Handling hanging responses:
app.use((req, res, next) => {
// *Checking if the status code has been set:
if(res.statusCode){
// *If it has:
// *Checking if the status code is different than 404:
if(res.statusCode != 404){
// *If it is:
// *Ending the response:
res.end();
} else{
// *Ending the response with a 'Resource not found' error:
// *If it's not:
// *Sending to the 404 middlewares:
next();
}
});

// *Getting each 'not found' middleware:
for(let not_found_middleware of not_found_middlewares){
// *Using it:
app.use(not_found_middleware);
}

// *Handling hanging responses (as the custom 404 middleware could left them hanging):
app.use((req, res, next) => {
// *Checking if the status code is different than 404:
if(res.statusCode != 404){
// *If it is:
// *Ending the response:
res.end();
} else{
// *If it's not:
// *Ending the response with a '404 NOT FOUND':
res.status(404).end();
}
});
Expand All @@ -251,6 +321,10 @@ function startServer({ server_port, index_file, static_resources, api_resources
throw new Error('The server port must be set');


// *Emitting the 'after setup' event:
ee.emit(HOOKS.AFTER_SETUP, app, express);


// *Starting up the server:
server = app.listen(app.locals.port, () => {
// *Starting the socket counter:
Expand Down Expand Up @@ -303,6 +377,7 @@ function stopServer(){

// *When the server closes:
server.close(err => {
server = null;
// *Resolving the promise:
resolve();
});
Expand Down
Loading

0 comments on commit 1f349a3

Please sign in to comment.