Query Builder: DB() e NEWDB() con il proprio driver di database
DB() costruisce una query senza sapere quale database la eseguirà, e NEWDB() registra il driver che la esegue. total5 stesso non ha un driver SQL: il query builder raccoglie ciò che chiedi in un oggetto options e chiama il tuo driver con esso, e il driver (il tuo, o uno fornito da un modulo) traduce options in SQL, in una chiamata NoSQL o in qualsiasi altra cosa.
NEWDB(driver)registra il driver predefinito eNEWDB('name', driver)uno con nome. Il driver èfunction(options, callback): rispondi concallback(error, response). Una tabella scritta comename/table(DB().find('audit/log')) usa il drivernamee la tabellalog; senza prefisso il driver èdefault.- Le operazioni iniziano la query:
find(table)e di un’arredita,read(table)Un oggetto onullQuando non c’è nessuno,list(table)(una pagina di un’array:response.page,limitepagesè aggiunto a ciò che il conducente ritorna, quindi il conducenti dovrebbecount) einsert(table, data)Anche il costruttore hacount,update,removeequeryIl conducente è in grado di lavorare allo stesso modo (il conducenteoptions.execcon questo nome). - Ripetere la domanda con:
where(name, [comparer], value)(=Quando non c’è paragone,fields('a,b'),sort(name, [true])(trueper la scadenza,take(n)epage(page, limit)Altre modifiche includonoid,in,skip,betweenesearch. - Concludi con
.callback($): il risultato va alla risposta dell'azione$, o a una funzione(err, response)che passi al suo posto.
Per il catalogo operativo nativo completo, il comportamento di errore e le forme di filtro, vedi Contratto di costruzionePer SQL CRUD, commo e rollback, vedere Query-costruttore-sqliteLe opzioni che il conducente riceve sono dati piatti. l'esempio del conducente memorizza i record e esprime l'ultimo oggetto ricevuto options.
const users = [
{ id: 1, name: 'Ann', age: 31 },
{ id: 2, name: 'Bob', age: 17 },
{ id: 3, name: 'Cy', age: 45 }
];
F.seen = [];
// The default driver: it understands only "age >= value" and "id = value", which is all this example asks
NEWDB(function(options, callback) {
F.seen.push(JSON.parse(JSON.stringify(options)));
let rows = users.slice();
for (let f of options.filter) {
if (f.type === 'where' && f.name === 'age' && f.comparer === '>=')
rows = rows.filter(n => n.age >= f.value);
else if (f.type === 'where' && f.name === 'id')
rows = rows.filter(n => n.id === f.value);
}
switch (options.exec) {
case 'find':
case 'read':
if (options.sort && options.sort[0] === 'name_desc')
rows.sort((a, b) => a.name < b.name ? 1 : -1);
if (options.take)
rows = rows.slice(0, options.take);
return callback(null, rows);
case 'list':
rows.count = rows.length;
return callback(null, rows);
case 'insert':
users.push(Object.assign({ id: users.length + 1 }, options.payload));
return callback(null, users[users.length - 1]);
default:
return callback('The driver does not know ' + options.exec);
}
});
// A second driver, used by the tables that start with "audit/"
NEWDB('audit', function(options, callback) {
F.seen.push({ driver: 'audit', table: options.table });
callback(null, [{ event: 'login' }]);
});exports.install = function() {
ROUTE('GET /adults/', adults);
ROUTE('GET /user/{id}/', user);
ROUTE('POST /users/', create);
ROUTE('GET /page/', page);
ROUTE('GET /audit/', audit);
ROUTE('GET /seen/', seen);
};
function adults($) {
DB().find('users').where('age', '>=', 18).fields('id,name').sort('name', true).take(5).callback($);
}
function user($) {
DB().read('users').where('id', +$.params.id).callback($);
}
function create($) {
DB().insert('users', { name: $.body.name, age: $.body.age }).callback($);
}
function page($) {
DB().list('users').page(1, 2).callback(function(err, response) {
$.json({ err: err, count: response.count, page: response.page, limit: response.limit, pages: response.pages });
});
}
function audit($) {
DB().find('audit/log').callback($);
}
function seen($) {
$.json(F.seen);
}