Skip to content

Commit

Permalink
Merge pull request #6 from Potentii/v2.2.1
Browse files Browse the repository at this point in the history
v2.2.1
  • Loading branch information
Potentii authored Jul 31, 2017
2 parents 481a864 + ed3edc0 commit 785bad5
Show file tree
Hide file tree
Showing 12 changed files with 209 additions and 32 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ server
_**See:**_

- [_StaticConfigurator_](docs/static-configurator.md)
- [*StaticConfigurator.prototype.add(route, resource\_path)*](docs/static-configurator.md#staticconfiguratorprototypeaddroute-resource_path)
- [*StaticConfigurator.prototype.add(route, resource\_path)*](docs/static-configurator.md#staticconfiguratorprototypeaddroute-resource_path-options)
- [_StaticConfigurator.prototype.index(file)_](docs/static-configurator.md#staticconfiguratorprototypeindexfile-options)

***
Expand Down
49 changes: 45 additions & 4 deletions docs/configurator.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,10 @@ _**Note:** calling this method will make the default server port to be `443` ins
#### Parameters

- `options` _object_ \- The HTTPS options object
- `cert` _string_ \- The HTTPS certificate
- `key` _string_ \- The HTTPS key
- `pfx` _string_ \- The HTTPS pfx
- `passphrase` _string_ \- The HTTPS pfx password
- `options.cert` _string_ \- The HTTPS certificate
- `options.key` _string_ \- The HTTPS key
- `options.pfx` _string_ \- The HTTPS pfx
- `options.passphrase` _string_ \- The HTTPS pfx password
- `is_file` _boolean_ \- Whether the options values are filenames, and should be retrieved from disk

#### Returns
Expand Down Expand Up @@ -194,6 +194,47 @@ server

<br>

### Configurator.prototype.locals(key, value)

Sets a new property in the Express `locals` (or the entire `locals` object).

_**Note:** if an object is passed, it will override the `locals` object. Otherwise, the arguments will be processed as a key and a value, and they will be merged into the `locals` object._

#### Parameters

- `key` _object|string_ \- The key of the value, or the entire `locals` object
- `value` _\*_ \- The value for the given key

#### Returns

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

#### Examples

Setting the entire `locals` object:

```javascript
server
.locals({
prop1: 'val1',
prop2: 'val2'
})
// other calls to 'locals()' method passing an object will override it
```

Using key\-value pairs:

```javascript
server
.locals('prop1', 'val1')
.locals('prop2', 'val2')
// calls to 'locals()' method passing an object will override it
```

***

<br>

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

Registers a handler for a given event.
Expand Down
10 changes: 7 additions & 3 deletions docs/static-configurator.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ _Array<{ route, path }>_ \- An array containing all the static resources
- `route` _string_ \- The server route
- `path` _string_ \- The absolute path to a file/directory in disk

_**Note:** readonly, use the_ [_`add()`_](#staticconfiguratorprototypeaddroute-resource_path) _method to add a new resource._
_**Note:** readonly, use the_ [_`add()`_](#staticconfiguratorprototypeaddroute-resource_path-options) _method to add a new resource._

***

Expand Down Expand Up @@ -70,14 +70,18 @@ server.static

<br>

### StaticConfigurator.prototype.add(route, resource\_path)
### StaticConfigurator.prototype.add(route, resource\_path, options)

Registers a static directory or file to be served on the given route

#### Parameters

- `route` _string_ \- The server route
- `resource_path` _string_ \- The relative/absolute file/directory path
- `options` _object_ \- The static options object
- `options.dotfiles` _string_ \- Express static `dotfiles` property
- `options.maxAge` _number_ \- Express static `maxAge` property
- `options.etag` _boolean_ \- Express static `etag` property

#### Returns

Expand All @@ -92,7 +96,7 @@ Registers a static directory or file to be served on the given route
```javascript
server.static
.add('/static/js', '../src/js')
.add('/static/css', '../src/css')
.add('/static/css', '../src/css', { dotfiles: 'allow' })
.add('/static/logo', '../src/images/logo.png');
```

Expand Down
10 changes: 9 additions & 1 deletion libs/booting/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
* @return {Promise} The server starting promise
* @author Guilherme Reginaldo Ruella
*/
function startServer({ server_port, secure, not_found_middlewares, index, static_resources, api_resources }, ee, sockets){
function startServer({ server_port, secure, locals, not_found_middlewares, index, static_resources, api_resources }, ee, sockets){
// *Returning the starting promise:
return new Promise((resolve, reject) => {
// *Requiring the needed modules:
Expand Down Expand Up @@ -124,6 +124,14 @@ function startServer({ server_port, secure, not_found_middlewares, index, static
if(!app.locals.port)
throw new Error('The server port must be set');

// *Checking if the locals is an object:
if(locals && typeof locals === 'object')
// *If it is:
// *Merging each property of the locals object into the Express locals object:
for(let prop_name in locals)
if(locals.hasOwnProperty(prop_name))
app.locals[prop_name] = locals[prop_name];


// *Emitting the 'after setup' event:
ee.emit(HOOKS.AFTER_SETUP, app, express);
Expand Down
11 changes: 7 additions & 4 deletions libs/booting/static.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,15 @@ function applyStaticResource(app, static_resources){
// *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){
for(let { route, path, options } of static_resources){
// *Serving the static resource:
app.use(route, express.static(path, {
index: false,
redirect: false,
setHeaders: static_middleware
setHeaders: static_middleware,
redirect: false,
index: false,
dotfiles: options.dotfiles,
maxAge: options.maxAge,
etag: options.etag
}));
}
}
Expand Down
44 changes: 39 additions & 5 deletions libs/configurator.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ module.exports = class Configurator{
*/
this._secure = null;

/**
* The Express locals object
* @type {object}
*/
this._locals = null;

/**
* Inner configurator for static resources
* @private
Expand Down Expand Up @@ -179,6 +185,33 @@ module.exports = class Configurator{



/**
* Sets a new property in the Express 'locals' (or the entire 'locals' object)
* If an object is passed, it will override the 'locals' object
* Otherwise, the arguments will be processed as a key and a value, and they will be merged into the 'locals' object
* @param {object|string} key The key of the value, or the entire 'locals' object
* @param {*} value The value for the given key
* @return {Configurator} This configurator (for method chaining)
*/
locals(key, value){
// *Checking if the first argument is an object:
if(arguments[0] && typeof arguments[0] === 'object'){
// *If it is:
// *Replacing the locals:
this._locals = arguments[0];
} else{
// *If it isn't:
// *Initializing the locals, if it isn't an object:
this._locals = this._locals && typeof this._locals === 'object' ? this._locals : {};
// *Setting the key-value in the locals:
this._locals[key] = value;
}
// *Returning this configurator:
return this;
}



/**
* Registers a handler for a given event
* @param {string} event The event name
Expand All @@ -204,12 +237,13 @@ module.exports = class Configurator{
// *If it isn't:
// *Setting the server start promise, and starting the server:
this._server_start_promise = boot_server.startServer({
server_port: this.server_port,
secure: this._secure,
not_found_middlewares: this._not_found_middlewares,
index: this._static._index,
static_resources: this._static.resources,
api_resources: this._api.resources
static_resources: this._static.resources,
api_resources: this._api.resources,
server_port: this.server_port,
secure: this._secure,
locals: this._locals,
index: this._static._index
}, this._ee, this._sockets)
// *When the server starts:
.then(output => {
Expand Down
23 changes: 15 additions & 8 deletions libs/static-configurator.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ module.exports = class StaticConfigurator{
* @throws {TypeError} If the file is not a string
* @throws {Error} If the file does not represent a path to a file
*/
index(file, options){
index(file, options = {}){
// *Checking if the file is a string, throwing an error if it isn't:
if(!(typeof file === 'string'))
throw new TypeError('The \"file\" must be a string');
Expand Down Expand Up @@ -84,12 +84,16 @@ module.exports = class StaticConfigurator{

/**
* Registers a static directory or file to be served on the given route
* @param {string} route The server route
* @param {string} resource_path The relative/absolute file/directory path
* @return {Configurator} This configurator (for method chaining)
* @throws {TypeError} If the resource path is not a string
* @param {string} route The server route
* @param {string} resource_path The relative/absolute file/directory path
* @param {object} [options] The static options object
* @param {string} [options.dotfiles] Express static 'dotfiles' property
* @param {number} [options.maxAge] Express static 'maxAge' property
* @param {boolean} [options.etag] Express static 'etag' property
* @return {Configurator} This configurator (for method chaining)
* @throws {TypeError} If the resource path is not a string
*/
add(route, resource_path){
add(route, resource_path, options = {}){
// *Checking if the resource path is a string, throwing an error if it isn't:
if(!(typeof resource_path === 'string'))
throw new TypeError('The \"resource path\" must be a string');
Expand All @@ -101,8 +105,11 @@ module.exports = class StaticConfigurator{
resource_path = path.join(path.dirname(stack()[1].getFileName()), resource_path);
}

// *Setting the options as an object (sinse the user could set it as number, boolean, etc):
options = options && typeof options === 'object' ? options : {};

// *Adding this resource into the array:
this._resources.push({ route, path: resource_path });
this._resources.push({ route, path: resource_path, options });
// *Returning this configurator:
return this;
}
Expand Down Expand Up @@ -131,7 +138,7 @@ module.exports = class StaticConfigurator{


/**
* Retrieves the static resources (array of '{ route, path }' objects)
* Retrieves the static resources (array of '{ route, path, options }' objects)
* @readonly
* @type {Array}
*/
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "w-srvr",
"version": "2.2.0",
"version": "2.2.1",
"description": "A simple web server configurator for Expressjs",
"author": "Guilherme Reginaldo Ruella <[email protected]>",
"license": "MIT",
Expand Down
37 changes: 33 additions & 4 deletions test/boot.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,28 @@ describe('Boot', function(){
});
});

it('sets the Express \'locals\' object', function(){
// *Defining the locals object:
const locals = {
a: 1,
b: 2,
c: 3
};

// *Setting the locals object and serving it:
return configurator.port(3000)
.locals(locals)
.api
.get('/', (req, res, next) => res.status(200).json(req.app.locals).end())
.done()
.start()
.then(({ address }) => {
// *Expecting the Express locals to be set:
return requestAsPromise(Configurator.METHODS.GET, address.href)
.then(res => expect(JSON.parse(res.response.body)).to.deep.include(locals));
});
});


describe('HTTPS', function(){

Expand Down Expand Up @@ -122,7 +144,7 @@ describe('Boot', function(){

});

it('ends responses chains', function(){
it('ends hanging response chains', function(){
// *Adding a route that tries to chain with others:
return configurator.port(3000)
.api
Expand Down Expand Up @@ -233,7 +255,7 @@ describe('Boot', function(){
// *Adding resources:
return configurator.port(3000)
.static
.add('/static', './mock/mock-src')
.add('/static', './mock/mock-src', { dotfiles: 'allow' })
.done()
// *Starting the server:
.start()
Expand All @@ -247,6 +269,13 @@ describe('Boot', function(){
expect(res.body.toString()).to.equal(fs.readFileSync(path.join(__dirname, './mock/mock-src/mock-file.txt'), 'utf8'));
}),

// *Testing if dotfiles are being supported:
requestAsPromise(Configurator.METHODS.GET, address.href + 'static/.txt')
.then(res => {
expect(res.response.statusCode).to.equal(200);
expect(res.body.toString()).to.equal(fs.readFileSync(path.join(__dirname, './mock/mock-src/.txt'), 'utf8'));
}),

// *Testing if a 404 response is being sent if the resource does not exist:
requestAsPromise(Configurator.METHODS.GET, address.href + 'static/mock-file-that-does-not-exists.txt')
.then(res => {
Expand Down Expand Up @@ -286,7 +315,7 @@ describe('Boot', function(){
expect(res.response.statusCode).to.equal(404);
})

])
]);
});
});

Expand Down Expand Up @@ -316,7 +345,7 @@ describe('Boot', function(){
expect(res.body.toString()).to.equal(fs.readFileSync(path.join(__dirname, './mock/mock-index.html'), 'utf8'));
})

])
]);
});
});

Expand Down
Loading

0 comments on commit 785bad5

Please sign in to comment.