Processing arrays can take quite a few bit of time, this is something that can directly impacts the loading speed of your page and depend of the computer and the browser your users use. When you think that a typical users can load your website with a netbook , or an iphone for that matter, speeding up search in large arrays can be a good way to optimize your code …
La nueva versión, revisada a fondo aquÃ, publicará individualmente páginas dinámicas para cada nueva entrada, en lugar de llevar a cabo una publicación estática de la página completa cada vez, lo que se supone que aligerará la carga sobre los ser
Aunque el HTML5 no está disponible en todos los navegadores, no es mala idea ir incluyendo en nuestras webs aplicaciones que hagan uso de HTML5, e ir dándole un poco de vidilla al asunto y no estar pendientes de Internet Explorer. Por ello, este script nos puede venir muy bien:
function detectBrowserCapabilities(){
var res = new Array();
res["userAgent"] = navigator.userAgent;
var hasWebWorkers = !!window.Worker;
res["workersFlag"] = "" + hasWebWorkers;
var hasGeolocation = !!navigator.geolocation;
res["geoFlag"] = "" + hasGeolocation;
if (hasGeolocation) {
document.styleSheets[0].cssRules[1].style.display = "block";
navigator.geolocation.getCurrentPosition(function(location) {
res["geoLat"] = location.coords.latitude;
res["geoLong"] = location.coords.longitude;
});
}
var hasDb = !!window.openDatabase;
res["dbFlag"] = "" + hasDb;
var videoElement = document.createElement("video");
var hasVideo = !!videoElement["canPlayType"];
var ogg = false;
var h264 = false;
if (hasVideo) {
ogg = videoElement.canPlayType('video/ogg; codecs="theora, vorbis"') || "no";
h264 = videoElement.canPlayType('video/mp4;
codecs="avc1.42E01E, mp4a.40.2"') || "no";
}
res["videoFlag"] = "" + hasVideo;
if (hasVideo){
var vStyle = document.styleSheets[0].cssRules[0].style;
vStyle.display = "block";
}
res["h264Flag"] = "" + h264;
res["oggFlag"] = "" + ogg;
return res;
}
Cualquiera que haya utilizado Flickr alguna vez debe conocer la opción para agregar notas dentro de una imagen (Add Note), esta opción muchas veces es ideal para señalar o comentar dentro de la foto. Con un poco de CSS se puede lograr algo similar, fun
Trikir es el primer clon de Twitter en español y por lo que he podido ver está bastante logrado. El funcionamiento es similar a Twitter y ya incorpora opciones que tiene Jaiku como incluir RSS de otras fuentes o blogs.
Boomerang es una librería desarrollada por Yahoo que permite medir diferentes aspectos de rendimiento de nuestra web desde la perspectiva del usuario final. Añadiendo un script y distintas funciones, podemos comprobar diversos aspectos de nuestra web como:
El tiempo que el usuario cree que tarda en cargarse la web
El tiempo de carga de contenido dinámico
El ancho de banda durante la carga de la página
Tiempo de carga de diferentes módulos, por ejemplo módulos de Twitter o Facebook
Como ya dije, esta aplicación estará basada en Mongodb, y usaremos mongoose como ODM.
El primer paso es instalar mongoose:
npm i mongoose
Una vez instalado crearemos un controlador que nos permita usar la BD en toda la aplicación Hapi.js. Para ello haremos uso de los decorate del servidor. Los decorations permite extender objectos ofrecidos por Hapi.js, en nuestro caso server y request. Usando un plugin nos conectaremos a mongodb usando mongoose y añadiremos ese objecto con los decorate.
Creamos el fichero /plugins/db.js con el siguiente código:
/**
* DB controller
*
* It uses Mongoose and "stores" it in the server and the request using `decorate`
*/const mongoose = require( 'mongoose' );
exports.plugin = {
name: 'db',
register: asyncfunction( server, options ) {
mongoose.connect( options.url, { useNewUrlParser: true } );
const db = mongoose.connection;
// eslint-disable-next-line
db.on( 'error', console.error.bind( console, 'connection error:' ) );
db.once( 'open', function() {
server.decorate( 'server', 'db', mongoose );
server.decorate( 'request', 'db', mongoose );
// eslint-disable-next-lineconsole.log( 'DB connected' );
} );
},
};
Para configurar la conectividad a mongodb tendremos que añadir los datos a la /config/index.js
Ya tenemos casi todo configurado, ahora vamos a empezar con un ejemplo creando un esquema de moongose que nos permite acceder a colecciones de mongodb.
Lo más común es tener una colección de usuarios, que tendrá los siguientes campos:
userName: de tipo String,
firstName: de tipo String,
lastName: de tipo String,
email: de tipo String,
role: que referencia a otro elemento de otra colección,
isEnabled: de tipo Boolean,
password: de tipo String,
resetPassword: un objeto representado por:
hash: de tipo String,
active: de tipo Boolean,
También crearemos un método estático que devuelva todos los elementos de la colección users para realizar pruebas:
/**
* User model based on Mongoose
*/const mongoose = require( 'mongoose' );
const Schema = mongoose.Schema;
// Mongoose schemaconst userSchema = new mongoose.Schema( {
userName: String,
firstName: String,
lastName: String,
email: String,
role: Schema.Types.ObjectId,
isEnabled: Boolean,
password: String,
resetPassword: {
hash: String,
active: Boolean,
},
} );
/**
* User static model findAll
*
* @returns {array}
*/
userSchema.static( 'findAll', asyncfunction() {
const result = awaitnewPromise( ( resolve, reject ) => {
this.model( 'User' ).find( {} ).exec( ( error, data ) => {
if ( error ) {
reject( error );
}
resolve( data );
} );
} );
return result;
} );
const User = mongoose.model( 'User', userSchema );
module.exports = User;
Ya está todo, ahora solo modificamos el handler de la ruta home.js para mostrar los valores de findAll:
Siempre viene bien hacernos un control para direcciones IP, que permita pegar toda la dirección ip y que se rellenen las cajas correctamente y que al pulsar el punto se mueva de caja, y la verdad es que tampoco es muy difÃcil de hacer.