ForgeTotal.js 5
it

Total.js 5

Query Builder: DB() e NEWDB() con il proprio driver di database

Total.js 5 · total5@0.0.19 databasequerybuilder Eseguita con Total.js 5

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 e NEWDB('name', driver) uno con nome. Il driver è function(options, callback): rispondi con callback(error, response). Una tabella scritta come name/table (DB().find('audit/log')) usa il driver name e la tabella log; senza prefisso il driver è default.
  • Le operazioni iniziano la query: find(table) e di un’arredita, read(table) Un oggetto o null Quando non c’è nessuno, list(table) (una pagina di un’array: response.page, limit e pages è aggiunto a ciò che il conducente ritorna, quindi il conducenti dovrebbe count) e insert(table, data)Anche il costruttore ha count, update, remove e queryIl conducente è in grado di lavorare allo stesso modo (il conducente options.exec con questo nome).
  • Ripetere la domanda con: where(name, [comparer], value) (= Quando non c’è paragone, fields('a,b'), sort(name, [true]) (true per la scadenza, take(n) e page(page, limit)Altre modifiche includono id, in, skip, between e search.
  • 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.

definitions/db.js
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' }]);
});
controllers/users.js
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);
}