kysely-mapper
Version:
Flexible Kysely-based utility for mapping between tables and objects
71 lines • 3.2 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import { CompilingMappingSelectQuery } from './compiling-select-query.js';
/**
* Mapping query for selecting rows from a database table.
*/
export class MappingSelectQuery {
constructor(db, qb, transforms) {
this.db = db;
this.qb = qb;
this.transforms = transforms;
}
/**
* Returns a compiling query that can be executed multiple times with
* different parameters (if any parameters were provided), but which only
* compiles the underlying Kysely query builder on the first execution.
* Frees the query builder on the first execution to reduce memory usage.
* @typeParam Parameters Record characterizing the parameter names and
* types that were previously embedded in the query, if any.
* @returns A compiling select query.
*/
compile() {
return new CompilingMappingSelectQuery(this.db, this.qb, this.transforms);
}
/**
* Modifies the underlying Kysely query builder. All columns given in
* `SelectedColumns` are already selected, but you can select additional
* columns or add column aliases.
* @param factory A function that takes the current query builder and
* returns a new query builder.
*/
modify(factory) {
return new MappingSelectQuery(this.db, factory(this.qb), this.transforms);
}
/**
* Retrieves zero or more rows from the table, using `selectTransform`
* (if provided) to map the rows to objects of type `SelectedObject`.
* @returns An array of objects for the selected rows, possibly empty.
*/
returnAll() {
return __awaiter(this, void 0, void 0, function* () {
const results = yield this.qb.execute();
return this.transforms.selectTransform === undefined
? results
: results.map(this.transforms.selectTransform);
});
}
/**
* Retrieves a single row from the table, using `selectTransform`
* (if provided) to map the row to an object of type `SelectedObject`.
* @returns An object for the selected rows, or null if not found.
*/
returnOne() {
return __awaiter(this, void 0, void 0, function* () {
const result = yield this.qb.executeTakeFirst();
if (!result)
return null;
return this.transforms.selectTransform === undefined
? result
: this.transforms.selectTransform(result);
});
}
}
//# sourceMappingURL=select-query.js.map