Change endpoint from persons to people

This commit is contained in:
xfarrow
2025-03-23 21:00:08 +01:00
parent 4ae263662c
commit d005193f63
7158 changed files with 700476 additions and 735 deletions

View File

@ -0,0 +1,80 @@
// FunctionHelper
// -------
// Used for adding functions from the builder
// Example usage: table.dateTime('datetime_to_date').notNull().defaultTo(knex.fn.now());
class FunctionHelper {
constructor(client) {
this.client = client;
}
now(precision) {
if (typeof precision === 'number') {
return this.client.raw(`CURRENT_TIMESTAMP(${precision})`);
}
return this.client.raw('CURRENT_TIMESTAMP');
}
uuid() {
switch (this.client.driverName) {
case 'sqlite3':
case 'better-sqlite3':
return this.client.raw(
"(lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6))))"
);
case 'mssql':
return this.client.raw('(NEWID())');
case 'pg':
case 'pgnative':
case 'cockroachdb':
return this.client.raw('(gen_random_uuid())');
case 'oracle':
case 'oracledb':
return this.client.raw('(random_uuid())');
case 'mysql':
case 'mysql2':
return this.client.raw('(UUID())');
default:
throw new Error(
`${this.client.driverName} does not have a uuid function`
);
}
}
uuidToBin(uuid, ordered = true) {
const buf = Buffer.from(uuid.replace(/-/g, ''), 'hex');
return ordered
? Buffer.concat([
buf.slice(6, 8),
buf.slice(4, 6),
buf.slice(0, 4),
buf.slice(8, 16),
])
: Buffer.concat([
buf.slice(0, 4),
buf.slice(4, 6),
buf.slice(6, 8),
buf.slice(8, 16),
]);
}
binToUuid(bin, ordered = true) {
const buf = Buffer.from(bin, 'hex');
return ordered
? [
buf.toString('hex', 4, 8),
buf.toString('hex', 2, 4),
buf.toString('hex', 0, 2),
buf.toString('hex', 8, 10),
buf.toString('hex', 10, 16),
].join('-')
: [
buf.toString('hex', 0, 4),
buf.toString('hex', 4, 6),
buf.toString('hex', 6, 8),
buf.toString('hex', 8, 10),
buf.toString('hex', 10, 16),
].join('-');
}
}
module.exports = FunctionHelper;

View File

@ -0,0 +1,59 @@
const Client = require('../client');
const QueryBuilder = require('../query/querybuilder');
const QueryInterface = require('../query/method-constants');
const makeKnex = require('./make-knex');
const { KnexTimeoutError } = require('../util/timeout');
const { resolveConfig } = require('./internal/config-resolver');
const SchemaBuilder = require('../schema/builder');
const ViewBuilder = require('../schema/viewbuilder');
const ColumnBuilder = require('../schema/columnbuilder');
const TableBuilder = require('../schema/tablebuilder');
function knex(config) {
const { resolvedConfig, Dialect } = resolveConfig(...arguments);
const newKnex = makeKnex(new Dialect(resolvedConfig));
if (resolvedConfig.userParams) {
newKnex.userParams = resolvedConfig.userParams;
}
return newKnex;
}
// Expose Client on the main Knex namespace.
knex.Client = Client;
knex.KnexTimeoutError = KnexTimeoutError;
knex.QueryBuilder = {
extend: function (methodName, fn) {
QueryBuilder.extend(methodName, fn);
QueryInterface.push(methodName);
},
};
knex.SchemaBuilder = {
extend: function (methodName, fn) {
SchemaBuilder.extend(methodName, fn);
},
};
knex.ViewBuilder = {
extend: function (methodName, fn) {
ViewBuilder.extend(methodName, fn);
},
};
knex.ColumnBuilder = {
extend: function (methodName, fn) {
ColumnBuilder.extend(methodName, fn);
},
};
knex.TableBuilder = {
extend: function (methodName, fn) {
TableBuilder.extend(methodName, fn);
},
};
module.exports = knex;

View File

@ -0,0 +1,57 @@
const Client = require('../../client');
const { SUPPORTED_CLIENTS } = require('../../constants');
const parseConnection = require('./parse-connection');
const { getDialectByNameOrAlias } = require('../../dialects');
function resolveConfig(config) {
let Dialect;
let resolvedConfig;
// If config is a string, try to parse it
const parsedConfig =
typeof config === 'string'
? Object.assign(parseConnection(config), arguments[2])
: config;
// If user provided no relevant parameters, use generic client
if (
arguments.length === 0 ||
(!parsedConfig.client && !parsedConfig.dialect)
) {
Dialect = Client;
}
// If user provided Client constructor as a parameter, use it
else if (typeof parsedConfig.client === 'function') {
Dialect = parsedConfig.client;
}
// If neither applies, let's assume user specified name of a client or dialect as a string
else {
const clientName = parsedConfig.client || parsedConfig.dialect;
if (!SUPPORTED_CLIENTS.includes(clientName)) {
throw new Error(
`knex: Unknown configuration option 'client' value ${clientName}. Note that it is case-sensitive, check documentation for supported values.`
);
}
Dialect = getDialectByNameOrAlias(clientName);
}
// If config connection parameter is passed as string, try to parse it
if (typeof parsedConfig.connection === 'string') {
resolvedConfig = Object.assign({}, parsedConfig, {
connection: parseConnection(parsedConfig.connection).connection,
});
} else {
resolvedConfig = Object.assign({}, parsedConfig);
}
return {
resolvedConfig,
Dialect,
};
}
module.exports = {
resolveConfig,
};

View File

@ -0,0 +1,87 @@
const { parse } = require('pg-connection-string');
const parsePG = parse;
const isWindows = process && process.platform && process.platform === 'win32';
/**
* @param str
* @returns {URL}
*/
function tryParse(str) {
try {
return new URL(str);
} catch (e) {
return null;
}
}
module.exports = function parseConnectionString(str) {
const parsed = tryParse(str);
const isDriveLetter = isWindows && parsed && parsed.protocol.length === 2;
if (!parsed || isDriveLetter) {
return {
client: 'sqlite3',
connection: {
filename: str,
},
};
}
let { protocol } = parsed;
if (protocol.slice(-1) === ':') {
protocol = protocol.slice(0, -1);
}
const isPG = ['postgresql', 'postgres'].includes(protocol);
return {
client: protocol,
connection: isPG ? parsePG(str) : connectionObject(parsed),
};
};
/**
* @param {URL} parsed
* @returns {{}}
*/
function connectionObject(parsed) {
const connection = {};
let db = parsed.pathname;
if (db[0] === '/') {
db = db.slice(1);
}
connection.database = db;
if (parsed.hostname) {
if (parsed.protocol.indexOf('mssql') === 0) {
connection.server = parsed.hostname;
} else {
connection.host = parsed.hostname;
}
}
if (parsed.port) {
connection.port = parsed.port;
}
if (parsed.username || parsed.password) {
connection.user = decodeURIComponent(parsed.username);
}
if (parsed.password) {
connection.password = decodeURIComponent(parsed.password);
}
if (parsed.searchParams) {
for (const [key, value] of parsed.searchParams.entries()) {
const isNestedConfigSupported = ['mysql:', 'mariadb:', 'mssql:'].includes(
parsed.protocol
);
if (isNestedConfigSupported) {
try {
connection[key] = JSON.parse(value);
} catch (err) {
connection[key] = value;
}
} else {
connection[key] = value;
}
}
}
return connection;
}

View File

@ -0,0 +1,345 @@
const { EventEmitter } = require('events');
const { Migrator } = require('../migrations/migrate/Migrator');
const Seeder = require('../migrations/seed/Seeder');
const FunctionHelper = require('./FunctionHelper');
const QueryInterface = require('../query/method-constants');
const merge = require('lodash/merge');
const batchInsert = require('../execution/batch-insert');
const { isObject } = require('../util/is');
const { setHiddenProperty } = require('../util/security');
// Javascript does not officially support "callable objects". Instead,
// you must create a regular Function and inject properties/methods
// into it. In other words: you can't leverage Prototype Inheritance
// to share the property/method definitions.
//
// To work around this, we're creating an Object Property Definition.
// This allow us to quickly inject everything into the `knex` function
// via the `Object.defineProperties(..)` function. More importantly,
// it allows the same definitions to be shared across `knex` instances.
const KNEX_PROPERTY_DEFINITIONS = {
client: {
get() {
return this.context.client;
},
set(client) {
this.context.client = client;
},
configurable: true,
},
userParams: {
get() {
return this.context.userParams;
},
set(userParams) {
this.context.userParams = userParams;
},
configurable: true,
},
schema: {
get() {
return this.client.schemaBuilder();
},
configurable: true,
},
migrate: {
get() {
return new Migrator(this);
},
configurable: true,
},
seed: {
get() {
return new Seeder(this);
},
configurable: true,
},
fn: {
get() {
return new FunctionHelper(this.client);
},
configurable: true,
},
};
// `knex` instances serve as proxies around `context` objects. So, calling
// any of these methods on the `knex` instance will forward the call to
// the `knex.context` object. This ensures that `this` will correctly refer
// to `context` within each of these methods.
const CONTEXT_METHODS = [
'raw',
'batchInsert',
'transaction',
'transactionProvider',
'initialize',
'destroy',
'ref',
'withUserParams',
'queryBuilder',
'disableProcessing',
'enableProcessing',
];
for (const m of CONTEXT_METHODS) {
KNEX_PROPERTY_DEFINITIONS[m] = {
value: function (...args) {
return this.context[m](...args);
},
configurable: true,
};
}
function makeKnex(client) {
// The object we're potentially using to kick off an initial chain.
function knex(tableName, options) {
return createQueryBuilder(knex.context, tableName, options);
}
redefineProperties(knex, client);
return knex;
}
function initContext(knexFn) {
const knexContext = knexFn.context || {};
Object.assign(knexContext, {
queryBuilder() {
return this.client.queryBuilder();
},
raw() {
return this.client.raw.apply(this.client, arguments);
},
batchInsert(table, batch, chunkSize = 1000) {
return batchInsert(this, table, batch, chunkSize);
},
// Creates a new transaction.
// If container is provided, returns a promise for when the transaction is resolved.
// If container is not provided, returns a promise with a transaction that is resolved
// when transaction is ready to be used.
transaction(container, _config) {
// Overload support of `transaction(config)`
if (!_config && isObject(container)) {
_config = container;
container = null;
}
const config = Object.assign({}, _config);
config.userParams = this.userParams || {};
if (config.doNotRejectOnRollback === undefined) {
config.doNotRejectOnRollback = true;
}
return this._transaction(container, config);
},
// Internal method that actually establishes the Transaction. It makes no assumptions
// about the `config` or `outerTx`, and expects the caller to handle these details.
_transaction(container, config, outerTx = null) {
if (container) {
const trx = this.client.transaction(container, config, outerTx);
return trx;
} else {
return new Promise((resolve, reject) => {
this.client.transaction(resolve, config, outerTx).catch(reject);
});
}
},
transactionProvider(config) {
let trx;
return () => {
if (!trx) {
trx = this.transaction(undefined, config);
}
return trx;
};
},
// Typically never needed, initializes the pool for a knex client.
initialize(config) {
return this.client.initializePool(config);
},
// Convenience method for tearing down the pool.
destroy(callback) {
return this.client.destroy(callback);
},
ref(ref) {
return this.client.ref(ref);
},
// Do not document this as public API until naming and API is improved for general consumption
// This method exists to disable processing of internal queries in migrations
disableProcessing() {
if (this.userParams.isProcessingDisabled) {
return;
}
this.userParams.wrapIdentifier = this.client.config.wrapIdentifier;
this.userParams.postProcessResponse =
this.client.config.postProcessResponse;
this.client.config.wrapIdentifier = null;
this.client.config.postProcessResponse = null;
this.userParams.isProcessingDisabled = true;
},
// Do not document this as public API until naming and API is improved for general consumption
// This method exists to enable execution of non-internal queries with consistent identifier naming in migrations
enableProcessing() {
if (!this.userParams.isProcessingDisabled) {
return;
}
this.client.config.wrapIdentifier = this.userParams.wrapIdentifier;
this.client.config.postProcessResponse =
this.userParams.postProcessResponse;
this.userParams.isProcessingDisabled = false;
},
withUserParams(params) {
const knexClone = shallowCloneFunction(knexFn); // We need to include getters in our clone
if (this.client) {
knexClone.client = Object.create(this.client.constructor.prototype); // Clone client to avoid leaking listeners that are set on it
merge(knexClone.client, this.client);
knexClone.client.config = Object.assign({}, this.client.config); // Clone client config to make sure they can be modified independently
if (this.client.config.password) {
setHiddenProperty(knexClone.client.config, this.client.config);
}
}
redefineProperties(knexClone, knexClone.client);
_copyEventListeners('query', knexFn, knexClone);
_copyEventListeners('query-error', knexFn, knexClone);
_copyEventListeners('query-response', knexFn, knexClone);
_copyEventListeners('start', knexFn, knexClone);
knexClone.userParams = params;
return knexClone;
},
});
if (!knexFn.context) {
knexFn.context = knexContext;
}
}
function _copyEventListeners(eventName, sourceKnex, targetKnex) {
const listeners = sourceKnex.listeners(eventName);
listeners.forEach((listener) => {
targetKnex.on(eventName, listener);
});
}
function redefineProperties(knex, client) {
// Allow chaining methods from the root object, before
// any other information is specified.
//
// TODO: `QueryBuilder.extend(..)` allows new QueryBuilder
// methods to be introduced via external components.
// As a side-effect, it also pushes the new method names
// into the `QueryInterface` array.
//
// The Problem: due to the way the code is currently
// structured, these new methods cannot be retroactively
// injected into existing `knex` instances! As a result,
// some `knex` instances will support the methods, and
// others will not.
//
// We should revisit this once we figure out the desired
// behavior / usage. For instance: do we really want to
// allow external components to directly manipulate `knex`
// data structures? Or, should we come up w/ a different
// approach that avoids side-effects / mutation?
//
// (FYI: I noticed this issue because I attempted to integrate
// this logic directly into the `KNEX_PROPERTY_DEFINITIONS`
// construction. However, `KNEX_PROPERTY_DEFINITIONS` is
// constructed before any `knex` instances are created.
// As a result, the method extensions were missing from all
// `knex` instances.)
for (let i = 0; i < QueryInterface.length; i++) {
const method = QueryInterface[i];
knex[method] = function () {
const builder = this.queryBuilder();
return builder[method].apply(builder, arguments);
};
}
Object.defineProperties(knex, KNEX_PROPERTY_DEFINITIONS);
initContext(knex);
knex.client = client;
knex.userParams = {};
// Hook up the "knex" object as an EventEmitter.
const ee = new EventEmitter();
for (const key in ee) {
knex[key] = ee[key];
}
// Unfortunately, something seems to be broken in Node 6 and removing events from a clone also mutates original Knex,
// which is highly undesirable
if (knex._internalListeners) {
knex._internalListeners.forEach(({ eventName, listener }) => {
knex.client.removeListener(eventName, listener); // Remove duplicates for copies
});
}
knex._internalListeners = [];
// Passthrough all "start" and "query" events to the knex object.
_addInternalListener(knex, 'start', (obj) => {
knex.emit('start', obj);
});
_addInternalListener(knex, 'query', (obj) => {
knex.emit('query', obj);
});
_addInternalListener(knex, 'query-error', (err, obj) => {
knex.emit('query-error', err, obj);
});
_addInternalListener(knex, 'query-response', (response, obj, builder) => {
knex.emit('query-response', response, obj, builder);
});
}
function _addInternalListener(knex, eventName, listener) {
knex.client.on(eventName, listener);
knex._internalListeners.push({
eventName,
listener,
});
}
function createQueryBuilder(knexContext, tableName, options) {
const qb = knexContext.queryBuilder();
if (!tableName)
knexContext.client.logger.warn(
'calling knex without a tableName is deprecated. Use knex.queryBuilder() instead.'
);
return tableName ? qb.table(tableName, options) : qb;
}
function shallowCloneFunction(originalFunction) {
const fnContext = Object.create(
Object.getPrototypeOf(originalFunction),
Object.getOwnPropertyDescriptors(originalFunction)
);
const knexContext = {};
const knexFnWrapper = (tableName, options) => {
return createQueryBuilder(knexContext, tableName, options);
};
const clonedFunction = knexFnWrapper.bind(fnContext);
Object.assign(clonedFunction, originalFunction);
clonedFunction.context = knexContext;
return clonedFunction;
}
module.exports = makeKnex;