code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
function View (req, res) {
if (!req || req.constructor.name !== 'IncomingMessage') {
throw new Error('Keystone.View Error: Express request object is required.');
}
if (!res || res.constructor.name !== 'ServerResponse') {
throw new Error('Keystone.View Error: Express response object is required.');
}
this.req = req;
this.res = res;
this.initQueue = []; // executed first in series
this.actionQueue = []; // executed second in parallel, if optional conditions are met
this.queryQueue = []; // executed third in parallel
this.renderQueue = []; // executed fourth in parallel
}
|
View Constructor
=================
Helper to simplify view logic in a Keystone application
@api public
|
View
|
javascript
|
keystonejs/keystone-classic
|
lib/view.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/view.js
|
MIT
|
check = function (value, path) {
var ctx = req;
var parts = path.split('.');
for (var i = 0; i < parts.length - 1; i++) {
if (!ctx[parts[i]]) {
return false;
}
ctx = ctx[parts[i]];
}
path = _.last(parts);
return (value === true && path in ctx) ? true : (ctx[path] === value);
}
|
Adds a method (or array of methods) to be executed in parallel
to the `init`, `action` or `render` queue.
@api public
|
check
|
javascript
|
keystonejs/keystone-classic
|
lib/view.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/view.js
|
MIT
|
QueryCallbacks = function (options) {
if (utils.isString(options)) {
options = { then: options };
} else {
options = options || {};
}
this.callbacks = {};
if (options.err) this.callbacks.err = options.err;
if (options.none) this.callbacks.none = options.none;
if (options.then) this.callbacks.then = options.then;
return this;
}
|
Adds a method (or array of methods) to be executed in parallel
to the `init`, `action` or `render` queue.
@api public
|
QueryCallbacks
|
javascript
|
keystonejs/keystone-classic
|
lib/view.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/view.js
|
MIT
|
function Page (key, options) {
if (!(this instanceof Page)) {
return new Page(key, options);
}
this.options = assign({}, options);
this.key = key;
this.fields = {};
}
|
Page Class
@param {String} key
@param {Object} options
@api public
|
Page
|
javascript
|
keystonejs/keystone-classic
|
lib/content/page.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/content/page.js
|
MIT
|
function html (path, options) {
html.super_.call(path, options);
}
|
HTML ContentType Constructor
@extends Field
@api public
|
html
|
javascript
|
keystonejs/keystone-classic
|
lib/content/types/html.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/content/types/html.js
|
MIT
|
function text (path, options) {
text.super_.call(path, options);
}
|
Text ContentType Constructor
@extends Field
@api public
|
text
|
javascript
|
keystonejs/keystone-classic
|
lib/content/types/text.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/content/types/text.js
|
MIT
|
function isMongoId (value) {
return MONGO_ID_REGEXP.test(value);
}
|
Creates multiple items in one or more Lists
|
isMongoId
|
javascript
|
keystonejs/keystone-classic
|
lib/core/createItems.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/core/createItems.js
|
MIT
|
function createItems (data, ops, callback) {
var keystone = this;
var options = {
verbose: false,
strict: true,
refs: null,
};
var dashes = '------------------------------------------------';
if (!_.isObject(data)) {
throw new Error('keystone.createItems() requires a data object as the first argument.');
}
if (_.isObject(ops)) {
_.extend(options, ops);
}
if (typeof ops === 'function') {
callback = ops;
}
var lists = _.keys(data);
var refs = options.refs || {};
var stats = {};
// logger function
function writeLog (data) {
console.log(keystone.get('name') + ': ' + data);
}
async.waterfall([
// create items
function (next) {
async.eachSeries(lists, function (key, doneList) {
var list = keystone.list(key);
var relationshipPaths = _.filter(list.fields, { type: 'relationship' }).map(function (i) { return i.path; });
if (!list) {
if (options.strict) {
return doneList({
type: 'invalid list',
message: 'List key ' + key + ' is invalid.',
});
}
if (options.verbose) {
writeLog('Skipping invalid list: ' + key);
}
return doneList();
}
if (!refs[list.key]) {
refs[list.key] = {};
}
stats[list.key] = {
singular: list.singular,
plural: list.plural,
created: 0,
warnings: 0,
};
var itemsProcessed = 0;
var totalItems = data[key].length;
if (options.verbose) {
writeLog(dashes);
writeLog('Processing list: ' + key);
writeLog('Items to create: ' + totalItems);
writeLog(dashes);
}
async.eachSeries(data[key], function (data, doneItem) {
itemsProcessed++;
// Evaluate function properties to allow generated values (excluding relationships)
_.keys(data).forEach(function (i) {
if (typeof data[i] === 'function' && relationshipPaths.indexOf(i) === -1) {
data[i] = data[i]();
if (options.verbose) {
writeLog('Generated dynamic value for [' + i + ']: ' + data[i]);
}
}
});
var doc = data.__doc = new list.model();
if (data.__ref) {
refs[list.key][data.__ref] = doc;
}
async.each(list.fieldsArray, function (field, doneField) {
// skip relationship fields on the first pass.
if (field.type !== 'relationship') {
// TODO: Validate items?
field.updateItem(doc, data, doneField);
} else {
doneField();
}
}, function (err) {
if (!err) {
if (options.verbose) {
var documentName = list.getDocumentName(doc);
writeLog('Creating item [' + itemsProcessed + ' of ' + totalItems + '] - ' + documentName);
}
doc.save(function (err) {
if (err) {
err.model = key;
err.data = data;
debug('error saving ', key);
} else {
stats[list.key].created++;
}
doneItem(err);
});
} else {
doneItem(err);
}
});
}, doneList);
}, next);
},
// link items
function (next) {
async.each(lists, function (key, doneList) {
var list = keystone.list(key);
var relationships = _.filter(list.fields, { type: 'relationship' });
if (!list || !relationships.length) {
return doneList();
}
var itemsProcessed = 0;
var totalItems = data[key].length;
if (options.verbose) {
writeLog(dashes);
writeLog('Processing relationships for: ' + key);
writeLog('Items to process: ' + totalItems);
writeLog(dashes);
}
async.each(data[key], function (srcData, doneItem) {
var doc = srcData.__doc;
var relationshipsUpdated = 0;
itemsProcessed++;
if (options.verbose) {
var documentName = list.getDocumentName(doc);
writeLog('Processing item [' + itemsProcessed + ' of ' + totalItems + '] - ' + documentName);
}
async.each(relationships, function (field, doneField) {
var fieldValue = null;
var refsLookup = null;
if (!field.path) {
writeLog('WARNING: Invalid relationship (undefined list path) [List: ' + key + ']');
stats[list.key].warnings++;
return doneField();
} else {
fieldValue = srcData[field.path];
}
if (!field.refList) {
if (fieldValue) {
writeLog('WARNING: Invalid relationship (undefined reference list) [list: ' + key + '] [path: ' + fieldValue + ']');
stats[list.key].warnings++;
}
return doneField();
}
if (!field.refList.key) {
writeLog('WARNING: Invalid relationship (undefined ref list key) [list: ' + key + '] [field.refList: ' + field.refList + '] [fieldValue: ' + fieldValue + ']');
stats[list.key].warnings++;
return doneField();
} else {
refsLookup = refs[field.refList.key];
}
if (!fieldValue) {
return doneField();
}
// populate relationships from saved refs
if (typeof fieldValue === 'function') {
relationshipsUpdated++;
var fn = fieldValue;
var argsRegExp = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var lists = fn.toString().match(argsRegExp)[1].split(',').map(function (i) { return i.trim(); });
var args = lists.map(function (i) {
return keystone.list(i);
});
var query = fn.apply(keystone, args);
query.exec(function (err, results) {
if (err) { debug('error ', err); }
if (field.many) {
doc.set(field.path, results || []);
} else {
doc.set(field.path, (results && results.length) ? results[0] : undefined);
}
doneField(err);
});
} else if (_.isArray(fieldValue)) {
if (field.many) {
var refsArr = _.compact(fieldValue.map(function (ref) {
return isMongoId(ref) ? ref : refsLookup && refsLookup[ref] && refsLookup[ref].id;
}));
if (options.strict && refsArr.length !== fieldValue.length) {
return doneField({
type: 'invalid ref',
srcData: srcData,
message: 'Relationship ' + list.key + '.' + field.path + ' contains an invalid reference.',
});
}
relationshipsUpdated++;
doc.set(field.path, refsArr);
doneField();
} else {
return doneField({
type: 'invalid data',
srcData: srcData,
message: 'Single-value relationship ' + list.key + '.' + field.path + ' provided as an array.',
});
}
} else if (typeof fieldValue === 'string') {
var refItem = isMongoId(fieldValue) ? fieldValue : refsLookup && refsLookup[fieldValue] && refsLookup[fieldValue].id;
if (!refItem) {
return options.strict ? doneField({
type: 'invalid ref',
srcData: srcData,
message: 'Relationship ' + list.key + '.' + field.path + ' contains an invalid reference: "' + fieldValue + '".',
}) : doneField();
}
relationshipsUpdated++;
doc.set(field.path, field.many ? [refItem] : refItem);
doneField();
} else if (fieldValue && fieldValue.id) {
relationshipsUpdated++;
doc.set(field.path, field.many ? [fieldValue.id] : fieldValue.id);
doneField();
} else {
return doneField({
type: 'invalid data',
srcData: srcData,
message: 'Relationship ' + list.key + '.' + field.path + ' contains an invalid data type.',
});
}
}, function (err) {
if (err) {
debug('error ', err);
return doneItem(err);
}
if (options.verbose) {
writeLog('Populated ' + utils.plural(relationshipsUpdated, '* relationship', '* relationships') + '.');
}
if (relationshipsUpdated) {
doc.save(doneItem);
} else {
doneItem();
}
});
}, doneList);
}, next);
},
], function (err) {
if (err) {
console.error(err);
if ('stack' in err) {
console.trace(err.stack);
}
return callback && callback(err);
}
var msg = '\nSuccessfully created:\n';
_.forEach(stats, function (list) {
msg += '\n* ' + utils.plural(list.created, '* ' + list.singular, '* ' + list.plural);
if (list.warnings) {
msg += '\n ' + utils.plural(list.warnings, '* warning', '* warnings');
}
});
stats.message = msg + '\n';
callback(null, stats);
});
}
|
Creates multiple items in one or more Lists
|
createItems
|
javascript
|
keystonejs/keystone-classic
|
lib/core/createItems.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/core/createItems.js
|
MIT
|
function writeLog (data) {
console.log(keystone.get('name') + ': ' + data);
}
|
Creates multiple items in one or more Lists
|
writeLog
|
javascript
|
keystonejs/keystone-classic
|
lib/core/createItems.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/core/createItems.js
|
MIT
|
function getOrphanedLists () {
if (!this.nav) {
return [];
}
return _.filter(this.lists, function (list, key) {
if (list.get('hidden')) return false;
return (!this.nav.by.list[key]) ? list : false;
}.bind(this));
}
|
Retrieves orphaned lists (those not in a nav section)
|
getOrphanedLists
|
javascript
|
keystonejs/keystone-classic
|
lib/core/getOrphanedLists.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/core/getOrphanedLists.js
|
MIT
|
function dispatchImporter (rel__dirname) {
function importer (from) {
debug('importing ', from);
var imported = {};
var joinPath = function () {
return '.' + path.sep + path.join.apply(path, arguments);
};
var fsPath = joinPath(path.relative(process.cwd(), rel__dirname), from);
fs.readdirSync(fsPath).forEach(function (name) {
var info = fs.statSync(path.join(fsPath, name));
debug('recur');
if (info.isDirectory()) {
imported[name] = importer(joinPath(from, name));
} else {
// only import files that we can `require`
var ext = path.extname(name);
var base = path.basename(name, ext);
if (require.extensions[ext]) {
imported[base] = require(path.join(rel__dirname, from, name));
} else {
debug('cannot require ', ext);
}
}
});
return imported;
}
return importer;
}
|
Returns a function that looks in a specified path relative to the current
directory, and returns all .js modules in it (recursively).
####Example:
var importRoutes = keystone.importer(__dirname);
var routes = {
site: importRoutes('./site'),
api: importRoutes('./api')
};
@param {String} rel__dirname
@api public
|
dispatchImporter
|
javascript
|
keystonejs/keystone-classic
|
lib/core/importer.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/core/importer.js
|
MIT
|
function importer (from) {
debug('importing ', from);
var imported = {};
var joinPath = function () {
return '.' + path.sep + path.join.apply(path, arguments);
};
var fsPath = joinPath(path.relative(process.cwd(), rel__dirname), from);
fs.readdirSync(fsPath).forEach(function (name) {
var info = fs.statSync(path.join(fsPath, name));
debug('recur');
if (info.isDirectory()) {
imported[name] = importer(joinPath(from, name));
} else {
// only import files that we can `require`
var ext = path.extname(name);
var base = path.basename(name, ext);
if (require.extensions[ext]) {
imported[base] = require(path.join(rel__dirname, from, name));
} else {
debug('cannot require ', ext);
}
}
});
return imported;
}
|
Returns a function that looks in a specified path relative to the current
directory, and returns all .js modules in it (recursively).
####Example:
var importRoutes = keystone.importer(__dirname);
var routes = {
site: importRoutes('./site'),
api: importRoutes('./api')
};
@param {String} rel__dirname
@api public
|
importer
|
javascript
|
keystonejs/keystone-classic
|
lib/core/importer.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/core/importer.js
|
MIT
|
joinPath = function () {
return '.' + path.sep + path.join.apply(path, arguments);
}
|
Returns a function that looks in a specified path relative to the current
directory, and returns all .js modules in it (recursively).
####Example:
var importRoutes = keystone.importer(__dirname);
var routes = {
site: importRoutes('./site'),
api: importRoutes('./api')
};
@param {String} rel__dirname
@api public
|
joinPath
|
javascript
|
keystonejs/keystone-classic
|
lib/core/importer.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/core/importer.js
|
MIT
|
function init (options) {
this.options(options);
return this;
}
|
Initialises Keystone with the provided options
|
init
|
javascript
|
keystonejs/keystone-classic
|
lib/core/init.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/core/init.js
|
MIT
|
function isAbsolutePath (value) {
return path.resolve(value) === path.normalize(value).replace(new RegExp(path.sep + '$'), '');
}
|
This file contains methods specific to dealing with Keystone's options.
All exports are added to the Keystone.prototype
|
isAbsolutePath
|
javascript
|
keystonejs/keystone-classic
|
lib/core/options.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/core/options.js
|
MIT
|
function redirect () {
if (arguments.length === 1 && utils.isObject(arguments[0])) {
_.extend(this._redirects, arguments[0]);
} else if (arguments.length === 2 && typeof arguments[0] === 'string' && typeof arguments[1] === 'string') {
this._redirects[arguments[0]] = arguments[1];
}
return this;
}
|
Adds one or more redirections (urls that are redirected when no matching
routes are found, before treating the request as a 404)
#### Example:
keystone.redirect('/old-route', 'new-route');
// or
keystone.redirect({
'old-route': 'new-route'
});
|
redirect
|
javascript
|
keystonejs/keystone-classic
|
lib/core/redirect.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/core/redirect.js
|
MIT
|
function start (events) {
if (typeof events === 'function') {
events = { onStart: events };
}
if (!events) events = {};
function fireEvent (name) {
if (typeof events[name] === 'function') {
events[name]();
}
}
process.on('uncaughtException', function (e) {
if (e.code === 'EADDRINUSE') {
console.log(dashes
+ keystone.get('name') + ' failed to start: address already in use\n'
+ 'Please check you are not already running a server on the specified port.\n');
process.exit();
} else {
console.log(e.stack || e);
process.exit(1);
}
});
this.initExpressApp();
var keystone = this;
var app = keystone.app;
this.openDatabaseConnection(function () {
fireEvent('onMount');
var ssl = keystone.get('ssl');
var unixSocket = keystone.get('unix socket');
var startupMessages = [`KeystoneJS v${keystone.version} started:`];
async.parallel([
// HTTP Server
function (done) {
if (ssl === 'only' || unixSocket) return done();
require('../../server/startHTTPServer')(keystone, app, function (err, msg) {
fireEvent('onHttpServerCreated');
startupMessages.push(msg);
done(err);
});
},
// HTTPS Server
function (done) {
if (!ssl || unixSocket) return done();
require('../../server/startSecureServer')(keystone, app, function () {
fireEvent('onHttpsServerCreated');
}, function (err, msg) {
startupMessages.push(msg);
done(err);
});
},
// Unix Socket
function (done) {
if (!unixSocket) return done();
require('../../server/startSocketServer')(keystone, app, function (err, msg) {
fireEvent('onSocketServerCreated');
startupMessages.push(msg);
done(err);
});
},
], function serversStarted (err, messages) {
if (keystone.get('logger')) {
console.log(dashes + startupMessages.join('\n') + dashes);
}
fireEvent('onStart');
});
});
return this;
}
|
Configures and starts a Keystone app in encapsulated mode.
Connects to the database, runs updates and listens for incoming requests.
Events are fired during initialisation to allow customisation, including:
- onMount
- onStart
- onHttpServerCreated
- onHttpsServerCreated
If the events argument is a function, it is assumed to be the started event.
@api public
|
start
|
javascript
|
keystonejs/keystone-classic
|
lib/core/start.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/core/start.js
|
MIT
|
function fireEvent (name) {
if (typeof events[name] === 'function') {
events[name]();
}
}
|
Configures and starts a Keystone app in encapsulated mode.
Connects to the database, runs updates and listens for incoming requests.
Events are fired during initialisation to allow customisation, including:
- onMount
- onStart
- onHttpServerCreated
- onHttpsServerCreated
If the events argument is a function, it is assumed to be the started event.
@api public
|
fireEvent
|
javascript
|
keystonejs/keystone-classic
|
lib/core/start.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/core/start.js
|
MIT
|
function wrapHTMLError (title, err) {
return '<html><head><meta charset=\'utf-8\'><title>Error</title>'
+ '<link rel=\'stylesheet\' href=\'/' + this.get('admin path') + '/styles/error.css\'>'
+ '</head><body><div class=\'error\'><h1 class=\'error-title\'>' + title + '</h1>'
+ '<div class="error-message">' + (err || '') + '</div></div></body></html>';
}
|
Wraps an error in simple HTML to be sent as a response to the browser
@api public
|
wrapHTMLError
|
javascript
|
keystonejs/keystone-classic
|
lib/core/wrapHTMLError.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/core/wrapHTMLError.js
|
MIT
|
function add () {
var add = function (obj, prefix) {
prefix = prefix || '';
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!obj[key]) {
throw new Error(
'Invalid value for schema path `' + prefix + key + '` in `' + this.key + '`.\n'
+ 'Did you misspell the field type?\n'
);
}
if (utils.isObject(obj[key]) && (!obj[key].constructor || obj[key].constructor.name === 'Object') && (!obj[key].type || obj[key].type.type)) {
if (Object.keys(obj[key]).length) {
// nested object, e.g. { last: { name: String }}
// matches logic in mongoose/Schema:add
this.schema.nested[prefix + key] = true;
add(obj[key], prefix + key + '.');
} else {
addField(prefix + key, obj[key]); // mixed type field
}
} else {
addField(prefix + key, obj[key]);
}
}
}.bind(this);
var addField = function (path, options) {
if (this.isReserved(path)) {
throw new Error('Path ' + path + ' on list ' + this.key + ' is a reserved path');
}
this.uiElements.push({
type: 'field',
field: this.field(path, options),
});
}.bind(this);
var args = Array.prototype.slice.call(arguments);
var self = this;
_.forEach(args, function (def) {
self.schemaFields.push(def);
if (typeof def === 'string') {
if (def === '>>>') {
self.uiElements.push({
type: 'indent',
});
} else if (def === '<<<') {
self.uiElements.push({
type: 'outdent',
});
} else {
self.uiElements.push({
type: 'heading',
heading: def,
options: {},
});
}
} else {
if (def.heading && typeof def.heading === 'string') {
self.uiElements.push({
type: 'heading',
heading: def.heading,
options: def,
});
} else {
add(def);
}
}
});
return this;
}
|
Adds one or more fields to the List
Based on Mongoose's Schema.add
|
add
|
javascript
|
keystonejs/keystone-classic
|
lib/list/add.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/add.js
|
MIT
|
function automap (field) {
if ((field.path in this.mappings) && !this.mappings[field.path]) {
this.map(field.path, field.path);
}
return this;
}
|
Checks to see if a field path matches a currently unmapped path, and
if so, adds a mapping for it.
|
automap
|
javascript
|
keystonejs/keystone-classic
|
lib/list/automap.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/automap.js
|
MIT
|
function buildSearchTextIndex () {
var idxDef = {};
for (var i = 0; i < this.searchFields.length; i++) {
var sf = this.searchFields[i];
if (!sf.path || !sf.field) continue;
// TODO: Allow fields to define their own `getTextIndex` method, so that
// each type can define the right options for their schema. This is unlikely
// to behave as expected for fields that aren't simple strings or names
// until that has been done. Should error if the field type doesn't support
// text indexing, as the list has been misconfigured.
// Does the field have a single path or does it use nested values (like 'name')
if (sf.field.paths) {
var nFields = sf.field.paths;
var nKeys = Object.keys(nFields);
for (var n = 0; n < nKeys.length; n++) {
idxDef[nFields[nKeys[n]]] = 'text';
}
}
else if (sf.field.path) {
idxDef[sf.field.path] = 'text';
}
}
// debug('text index for \'' + this.key + '\':', idxDef);
return Object.keys(idxDef).length > 0 ? idxDef : false;
}
|
Returns either false if the list has no search fields defined or a structure
describing the text index that should exist.
|
buildSearchTextIndex
|
javascript
|
keystonejs/keystone-classic
|
lib/list/buildSearchTextIndex.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/buildSearchTextIndex.js
|
MIT
|
function declaresTextIndex () {
var indexes = this.schema.indexes();
for (var i = 0; i < indexes.length; i++) {
var fields = indexes[i][0];
var fieldNames = Object.keys(fields);
for (var h = 0; h < fieldNames.length; h++) {
var val = fields[fieldNames[h]];
if (typeof val === 'string' && val.toLowerCase() === 'text') return true;
}
}
return false;
}
|
Look for a text index defined in the current list schema; returns boolean
Note this doesn't check for text indexes that exist in the DB
|
declaresTextIndex
|
javascript
|
keystonejs/keystone-classic
|
lib/list/declaresTextIndex.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/declaresTextIndex.js
|
MIT
|
function ensureTextIndex (callback) {
var list = this;
var collection = list.model.collection;
var textIndex = list.buildSearchTextIndex();
var fieldsHash = Math.abs(hashString(Object.keys(textIndex).sort().join(';')));
var indexNamePrefix = 'keystone_searchFields_textIndex_';
var newIndexName = indexNamePrefix + fieldsHash;
// We use this later to create a new index if needed
var createNewIndex = function () {
collection.createIndex(textIndex, { name: newIndexName }, function (result) {
debug('collection.createIndex() result for \'' + list.key + '\:', result);
return callback();
});
};
collection.getIndexes(function (err, indexes) {
if (err) {
if (err.code === 26) {
// if the database doesn't exist, we'll get error code 26 "no database" here
// that's fine, we just default the indexes object so the new text index
// gets created when the database is connected.
indexes = {};
} else {
// otherwise, we've had an unexpected error, so we throw it
throw err;
}
}
var indexNames = Object.keys(indexes);
// Search though the
for (var i = 0; i < indexNames.length; i++) {
var existingIndexName = indexNames[i];
var isText = false;
// Check we're dealing with a text index
for (var h = 0; h < indexes[existingIndexName].length; h++) {
var column = indexes[existingIndexName][h];
if (column[1] === 'text') isText = isText || true;
}
// Skip non-text indexes
if (!isText) continue;
// Already exists with correct def
if (existingIndexName === newIndexName) {
debug('Existing text index \'' + existingIndexName + '\' already matches the searchFields for \'' + list.key + '\'');
return;
}
// Exists but hash (def) doesn't match
// Check for 'searchFields_text_index' for backwards compatibility
if (existingIndexName.slice(0, indexNamePrefix.length) === indexNamePrefix || existingIndexName === 'searchFields_text_index') {
debug('Existing text index \'' + existingIndexName + '\' doesn\'t match the searchFields for \'' + list.key + '\' and will be recreated as \'' + newIndexName + '\'');
collection.dropIndex(existingIndexName, function (result) {
debug('collection.dropIndex() result for \'' + list.key + '\:', result);
createNewIndex();
});
return;
}
// It's a text index but not one of ours; nothing we can do
console.error(''
+ 'list.ensureTextIndex() failed to update the existing text index \'' + existingIndexName + '\' for the \'' + list.key + '\' list.\n'
+ 'The existing index wasn\'t automatically created by ensureTextIndex() so will not be replaced.\n'
+ 'This may lead to unexpected behaviour when performing text searches on the this list.'
);
return;
}
// No text indexes found at all; create ours now
debug('No existing text index found in \'' + list.key + '\'; Creating ours now');
createNewIndex();
});
}
|
Does what it can to ensure the collection has an appropriate text index.
Works around unreliable behaviour with the Mongo drivers ensureIndex()
Specifically, when the following are true..
- Relying on collection.ensureIndexes() to create text indexes
- A text index already exists on the collection
- The existing index has a different definition but the same name
The index is not created/updated and no error is returned, either by the
ensureIndexes() call or the connection error listener.
Or at least that's what was happening for me (mongoose v3.8.40, mongodb v1.4.38)..
|
ensureTextIndex
|
javascript
|
keystonejs/keystone-classic
|
lib/list/ensureTextIndex.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/ensureTextIndex.js
|
MIT
|
createNewIndex = function () {
collection.createIndex(textIndex, { name: newIndexName }, function (result) {
debug('collection.createIndex() result for \'' + list.key + '\:', result);
return callback();
});
}
|
Does what it can to ensure the collection has an appropriate text index.
Works around unreliable behaviour with the Mongo drivers ensureIndex()
Specifically, when the following are true..
- Relying on collection.ensureIndexes() to create text indexes
- A text index already exists on the collection
- The existing index has a different definition but the same name
The index is not created/updated and no error is returned, either by the
ensureIndexes() call or the connection error listener.
Or at least that's what was happening for me (mongoose v3.8.40, mongodb v1.4.38)..
|
createNewIndex
|
javascript
|
keystonejs/keystone-classic
|
lib/list/ensureTextIndex.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/ensureTextIndex.js
|
MIT
|
function expandColumns (cols) {
if (typeof cols === 'string') {
cols = cols.split(',');
}
if (!Array.isArray(cols)) {
throw new Error('List.expandColumns: cols must be an array.');
}
var list = this;
var expanded = [];
var nameCol = false;
var getCol = function (def) {
if (def.path === '__name__') {
def.path = list.namePath;
}
var field = list.fields[def.path];
var col = null;
if (field) {
col = {
field: field,
path: field.path,
type: field.type,
label: def.label || field.label,
};
if (col.type === 'relationship') {
col.refList = col.field.refList;
if (col.refList) {
col.refPath = def.subpath || col.refList.namePath;
col.subField = col.refList.fields[col.refPath];
col.populate = { path: col.field.path, subpath: col.refPath };
}
if (!def.label && def.subpath) {
col.label = field.label + ': ' + (col.subField ? col.subField.label : utils.keyToLabel(def.subpath));
}
}
} else if (list.model.schema.paths[def.path] || list.model.schema.virtuals[def.path]) {
// column refers to a path in the schema
// TODO: this needs to handle sophisticated types, including arrays, nested Schemas, and mixed types
col = {
path: def.path,
label: def.label || utils.keyToLabel(def.path),
};
}
if (col) {
col.width = def.width;
if (col.path === list.namePath) {
col.isName = true;
nameCol = col;
}
if (field && field.col) {
_.extend(col, field.col);
}
}
return col;
};
for (var i = 0; i < cols.length; i++) {
var def = {};
if (typeof cols[i] === 'string') {
var parts = cols[i].trim().split('|');
def.width = parts[1] || false;
parts = parts[0].split(':');
def.path = parts[0];
def.subpath = parts[1];
}
if (!utils.isObject(def) || !def.path) {
throw new Error('List.expandColumns: column definition must contain a path.');
}
var col = getCol(def);
if (col) {
expanded.push(col);
}
}
if (!nameCol) {
nameCol = getCol({ path: list.namePath });
if (nameCol) {
expanded.unshift(nameCol);
}
}
return expanded;
}
|
Expands a comma-separated string or array of columns into valid column objects.
Columns can be:
- A Field, in the format "field|width"
- A Field in a single related List, in the format "list:field|width"
- Any valid path in the Schema, in the format "path|width"
The width part is optional, and can be in the format "n%" or "npx".
The path __name__ is automatically mapped to the namePath of the List.
The field or path for the name of the item (defaults to ID if not set or detected)
is automatically prepended if not explicitly included.
|
expandColumns
|
javascript
|
keystonejs/keystone-classic
|
lib/list/expandColumns.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/expandColumns.js
|
MIT
|
getCol = function (def) {
if (def.path === '__name__') {
def.path = list.namePath;
}
var field = list.fields[def.path];
var col = null;
if (field) {
col = {
field: field,
path: field.path,
type: field.type,
label: def.label || field.label,
};
if (col.type === 'relationship') {
col.refList = col.field.refList;
if (col.refList) {
col.refPath = def.subpath || col.refList.namePath;
col.subField = col.refList.fields[col.refPath];
col.populate = { path: col.field.path, subpath: col.refPath };
}
if (!def.label && def.subpath) {
col.label = field.label + ': ' + (col.subField ? col.subField.label : utils.keyToLabel(def.subpath));
}
}
} else if (list.model.schema.paths[def.path] || list.model.schema.virtuals[def.path]) {
// column refers to a path in the schema
// TODO: this needs to handle sophisticated types, including arrays, nested Schemas, and mixed types
col = {
path: def.path,
label: def.label || utils.keyToLabel(def.path),
};
}
if (col) {
col.width = def.width;
if (col.path === list.namePath) {
col.isName = true;
nameCol = col;
}
if (field && field.col) {
_.extend(col, field.col);
}
}
return col;
}
|
Expands a comma-separated string or array of columns into valid column objects.
Columns can be:
- A Field, in the format "field|width"
- A Field in a single related List, in the format "list:field|width"
- Any valid path in the Schema, in the format "path|width"
The width part is optional, and can be in the format "n%" or "npx".
The path __name__ is automatically mapped to the namePath of the List.
The field or path for the name of the item (defaults to ID if not set or detected)
is automatically prepended if not explicitly included.
|
getCol
|
javascript
|
keystonejs/keystone-classic
|
lib/list/expandColumns.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/expandColumns.js
|
MIT
|
function field (path, options) {
var Field = this.keystone.Field;
if (arguments.length === 1) {
return this.fields[path];
}
if (typeof options === 'function') {
options = { type: options };
}
if (this.get('noedit')) {
options.noedit = true;
}
if (!options.note && this.get('notes')) {
options.note = this.get('notes')[path];
}
if (typeof options.type !== 'function') {
throw new Error('Fields must be specified with a type function');
}
if (!(options.type.prototype instanceof Field)) {
// Convert native field types to their default Keystone counterpart
if (options.type === String) {
options.type = Field.Types.Text;
} else if (options.type === Number) {
options.type = Field.Types.Number;
} else if (options.type === Boolean) {
options.type = Field.Types.Boolean;
} else if (options.type === Date) {
options.type = Field.Types.Datetime;
} else {
throw new Error('Unrecognised field constructor: ' + options.type);
}
}
// Note the presence of this field type for client-side script optimisation
this.fieldTypes[options.type.name] = options.type.properName;
// Wysiwyg HTML fields are handled as a special case so we can include TinyMCE as required
if (options.type.name === 'html' && options.wysiwyg) {
this.fieldTypes.wysiwyg = true;
}
var field = new options.type(this, path, options);
this.fields[path] = field;
this.fieldsArray.push(field);
if (field.type === 'relationship') {
this.relationshipFields.push(field);
}
return field;
}
|
Creates a new field at the specified path, with the provided options.
If no options are provides, returns the field at the specified path.
|
field
|
javascript
|
keystonejs/keystone-classic
|
lib/list/field.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/field.js
|
MIT
|
function getAdminURL (item) {
return '/' + this.keystone.get('admin path') + '/' + this.path + (item ? '/' + item.id : '');
}
|
Gets the Admin URL to view the list (or an item if provided)
Example:
var listURL = list.getAdminURL()
var itemURL = list.getAdminURL(item)
@param {Object} item
|
getAdminURL
|
javascript
|
keystonejs/keystone-classic
|
lib/list/getAdminURL.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/getAdminURL.js
|
MIT
|
function transformFieldValue (field, item, options) {
var transform = typeof field.options.toCSV === 'string'
? listToArray(field.options.toCSV)
: field.options.toCSV;
if (typeof transform === 'function') {
return transform.call(item, field, options);
}
if (Array.isArray(transform)) {
var value = item.get(field.path);
if (transform.length === 1) {
return value[transform[0]];
} else {
return _.pick(value, transform);
}
}
return field.format(item);
}
|
Applies option field transforms to get the CSV value for a field
|
transformFieldValue
|
javascript
|
keystonejs/keystone-classic
|
lib/list/getCSVData.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/getCSVData.js
|
MIT
|
function getCSVData (item, options) {
if (!options) {
options = {};
}
options.fields;
if (options.fields === undefined) {
options.fields = Object.keys(this.options.fields);
}
var data = {
id: String(item.id),
};
if (this.autokey) {
data[this.autokey.path] = item.get(this.autokey.path);
}
if (options.fields) {
if (typeof options.fields === 'string') {
options.fields = listToArray(options.fields);
}
if (!Array.isArray(options.fields)) {
throw new Error('List.getCSV: options.fields must be undefined, a string, or an array.');
}
options.fields.forEach(function (path) {
var field = this.fields[path];
if (!field) {
// if the path isn't actually a field, just add the value from
// that path in the mongoose document.
data[path] = item.get(path);
return;
}
if (field.type !== 'relationship' || !options.expandRelationshipFields) {
// use the transformFieldValue function to get the data
data[path] = transformFieldValue(field, item, options);
return;
}
// relationship values should be expanded into separate name and
// id pairs using the field's getExpandedData method.
var expanded = field.getExpandedData(item);
if (field.many) {
// for many-type relationships, ensure the value is an array,
// and turn it into a list of 'name (id)' values
data[path] = (Array.isArray(expanded) ? expanded : []).map(function (i) {
return i.name ? i.name + ' (' + i.id + ')' : i.id;
}).join(', ');
} else if (typeof expanded === 'object') {
// for single-type relationships, add two columns to the data
data[path] = expanded.name;
data[path + 'Id'] = expanded.id;
}
}, this);
}
if (typeof item.getCSVData === 'function') {
var ext = item.getCSVData(data, options);
if (typeof ext === 'object') {
_.forOwn(ext, function (value, key) {
if (value === undefined) {
delete data[key];
} else {
data[key] = value;
}
});
}
}
// Copy each value into the return structure, flattening arrays into lists and
// flattening objects into a column per property (one level only)
var rtn = {};
_.forOwn(data, function (value, prop) {
if (Array.isArray(value)) {
// Array values are serialised to JSON, this should be an edge-case catch
// for data coming raw from the item; array-type fields will already have
// been stringified by the field.format method.
rtn[prop] = JSON.stringify(value);
} else if (typeof value === 'object') {
// For object values, we loop through each key and add it to its own column
// in the csv. Complex values are serialised to JSON.
_.forOwn(value, function (v, i) {
var suffix = i.substr(0, 1).toUpperCase() + i.substr(1);
rtn[prop + suffix] = (typeof v === 'object') ? JSON.stringify(v) : v;
});
} else {
rtn[prop] = value;
}
});
// Prevent CSV macro injection
_.forOwn(rtn, (value, prop) => {
rtn[prop] = escapeValueForExcel(value);
});
return rtn;
}
|
Gets the data from an Item ready to be serialised to CSV for download
|
getCSVData
|
javascript
|
keystonejs/keystone-classic
|
lib/list/getCSVData.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/getCSVData.js
|
MIT
|
function getData (item, fields, expandRelationshipFields) {
var data = {
id: item.id,
name: this.getDocumentName(item),
};
if (this.autokey) {
data[this.autokey.path] = item.get(this.autokey.path);
}
if (this.options.sortable) {
data.sortOrder = item.sortOrder;
}
if (fields === undefined) {
fields = Object.keys(this.fields);
}
if (fields) {
if (typeof fields === 'string') {
fields = listToArray(fields);
}
if (!Array.isArray(fields)) {
throw new Error('List.getData: fields must be undefined, a string, or an array.');
}
data.fields = {};
fields.forEach(function (path) {
var field = this.fields[path];
if (field) {
if (field.type === 'relationship' && expandRelationshipFields) {
data.fields[path] = field.getExpandedData(item);
} else {
data.fields[path] = field.getData(item);
}
} else {
data.fields[path] = item.get(path);
}
}, this);
}
return data;
}
|
Gets the data from an Item ready to be serialised for client-side use, as
used by the React components and the Admin API
|
getData
|
javascript
|
keystonejs/keystone-classic
|
lib/list/getData.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/getData.js
|
MIT
|
function getDocumentName (doc, escape) {
// console.log('getting document name for ' + doc.id, 'nameField: ' + this.nameField, 'namePath: ' + this.namePath);
// console.log('raw name value: ', doc.get(this.namePath));
// if (this.nameField) console.log('formatted name value: ', this.nameField.format(doc));
var name = String(this.nameField ? this.nameField.format(doc) : doc.get(this.namePath));
return (escape) ? utils.encodeHTMLEntities(name) : name;
}
|
Gets the name of the provided document from the correct path
Example:
var name = list.getDocumentName(item)
@param {Object} item
@param {Boolean} escape - causes HTML entities to be encoded
|
getDocumentName
|
javascript
|
keystonejs/keystone-classic
|
lib/list/getDocumentName.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/getDocumentName.js
|
MIT
|
function getOptions () {
var ops = {
autocreate: this.options.autocreate,
autokey: this.autokey,
defaultColumns: this.options.defaultColumns,
defaultSort: this.options.defaultSort,
fields: {},
hidden: this.options.hidden,
initialFields: _.map(this.initialFields, 'path'),
key: this.key,
label: this.label,
nameField: this.nameField ? this.nameField.getOptions() : null,
nameFieldIsFormHeader: this.nameFieldIsFormHeader,
nameIsInitial: this.nameIsInitial,
nameIsVirtual: this.nameIsVirtual,
namePath: this.namePath,
nocreate: this.options.nocreate,
nodelete: this.options.nodelete,
noedit: this.options.noedit,
path: this.path,
perPage: this.options.perPage,
plural: this.plural,
searchFields: this.options.searchFields,
singular: this.singular,
sortable: this.options.sortable,
sortContext: this.options.sortContext,
track: this.options.track,
tracking: this.tracking,
relationships: this.relationships,
uiElements: [],
};
_.forEach(this.uiElements, function (el) {
switch (el.type) {
// TODO: handle indentation
case 'field':
// add the field options by path
ops.fields[el.field.path] = el.field.getOptions();
// don't output hidden fields
if (el.field.hidden) {
return;
}
// add the field to the elements array
ops.uiElements.push({
type: 'field',
field: el.field.path,
});
break;
case 'heading':
ops.uiElements.push({
type: 'heading',
content: el.heading,
options: el.options,
});
break;
}
});
return ops;
}
|
Gets the options for the List, as used by the React components
|
getOptions
|
javascript
|
keystonejs/keystone-classic
|
lib/list/getOptions.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/getOptions.js
|
MIT
|
function getPages (options, maxPages) {
var surround = Math.floor(maxPages / 2);
var firstPage = maxPages ? Math.max(1, options.currentPage - surround) : 1;
var padRight = Math.max(((options.currentPage - surround) - 1) * -1, 0);
var lastPage = maxPages ? Math.min(options.totalPages, options.currentPage + surround + padRight) : options.totalPages;
var padLeft = Math.max(((options.currentPage + surround) - lastPage), 0);
options.pages = [];
firstPage = Math.max(Math.min(firstPage, firstPage - padLeft), 1);
for (var i = firstPage; i <= lastPage; i++) {
options.pages.push(i);
}
if (firstPage !== 1) {
options.pages.shift();
options.pages.unshift('...');
}
if (lastPage !== Number(options.totalPages)) {
options.pages.pop();
options.pages.push('...');
}
}
|
Generate page array for pagination
@param {Number} the maximum number pages to display in the pagination
@param {Object} page options
|
getPages
|
javascript
|
keystonejs/keystone-classic
|
lib/list/getPages.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/getPages.js
|
MIT
|
function getSearchFilters (search, add) {
var filters = {};
var list = this;
search = String(search || '').trim();
if (search.length) {
// Use the text index the behaviour is enabled by the list schema
// Usually, when searchUsesTextIndex is true, list.register() will maintain an index using ensureTextIndex()
// However, it's possible for searchUsesTextIndex to be true while there is an existing text index on the collection that *isn't* described in the list schema
// If this occurs, an error will be reported when list.register() is called and the existing index will not be replaced, meaning it will be used here
if (this.options.searchUsesTextIndex) {
filters.$text = { $search: search };
}
else {
var searchFilter;
var searchParts = search.split(' ');
var searchRx = new RegExp(utils.escapeRegExp(search), 'i');
var splitSearchRx = new RegExp((searchParts.length > 1) ? _.map(searchParts, utils.escapeRegExp).join('|') : search, 'i');
var searchFields = this.get('searchFields');
var searchFilters = [];
var searchIdField = utils.isValidObjectId(search);
if (typeof searchFields === 'string') {
searchFields = searchFields.split(',');
}
searchFields.forEach(function (path) {
path = path.trim();
if (path === '__name__') {
path = list.mappings.name;
}
var field = list.fields[path];
if (field && field.type === 'name') {
var first = {};
first[field.paths.first] = splitSearchRx;
var last = {};
last[field.paths.last] = splitSearchRx;
searchFilter = {};
searchFilter.$or = [first, last];
searchFilters.push(searchFilter);
} else {
searchFilter = {};
searchFilter[path] = searchRx;
searchFilters.push(searchFilter);
}
});
if (list.autokey) {
searchFilter = {};
searchFilter[list.autokey.path] = searchRx;
searchFilters.push(searchFilter);
}
if (searchIdField) {
searchFilter = {};
searchFilter._id = search;
searchFilters.push(searchFilter);
}
if (searchFilters.length > 1) {
filters.$or = searchFilters;
} else if (searchFilters.length) {
filters = searchFilters[0];
}
}
}
if (add) {
_.forEach(add, function (filter) {
var cond;
var path = filter.key;
var value = filter.value;
switch (filter.field.type) {
case 'boolean':
if (!value || value === 'false') {
filters[path] = { $ne: true };
} else {
filters[path] = true;
}
break;
case 'localfile':
case 'cloudinaryimage':
case 'cloudinaryimages':
case 's3file':
case 'name':
case 'password':
// TODO
break;
case 'location':
_.forEach(['street1', 'suburb', 'state', 'postcode', 'country'], function (pathKey, i) {
var value = filter.value[i];
if (value) {
filters[filter.field.paths[pathKey]] = new RegExp(utils.escapeRegExp(value), 'i');
}
});
break;
case 'relationship':
if (value) {
if (filter.field.many) {
filters[path] = (filter.inverse) ? { $nin: [value] } : { $in: [value] };
} else {
filters[path] = (filter.inverse) ? { $ne: value } : value;
}
} else {
if (filter.field.many) {
filters[path] = (filter.inverse) ? { $not: { $size: 0 } } : { $size: 0 };
} else {
filters[path] = (filter.inverse) ? { $ne: null } : null;
}
}
break;
case 'select':
if (filter.value) {
filters[path] = (filter.inverse) ? { $ne: value } : value;
} else {
filters[path] = (filter.inverse) ? { $nin: ['', null] } : { $in: ['', null] };
}
break;
case 'number':
case 'money':
if (filter.operator === 'bt') {
value = [
utils.number(value[0]),
utils.number(value[1]),
];
if (!isNaN(value[0]) && !isNaN(value[1])) {
filters[path] = {
$gte: value[0],
$lte: value[1],
};
}
else {
filters[path] = null;
}
} else {
value = utils.number(value);
if (!isNaN(value)) {
if (filter.operator === 'gt') {
filters[path] = { $gt: value };
}
else if (filter.operator === 'lt') {
filters[path] = { $lt: value };
}
else {
filters[path] = value;
}
}
else {
filters[path] = null;
}
}
break;
case 'date':
case 'datetime':
if (filter.operator === 'bt') {
value = [
moment(value[0]),
moment(value[1]),
];
if ((value[0] && value[0].isValid()) && (value[1] && value[0].isValid())) {
filters[path] = {
$gte: moment(value[0]).startOf('day').toDate(),
$lte: moment(value[1]).endOf('day').toDate(),
};
}
} else {
value = moment(value);
if (value && value.isValid()) {
var start = moment(value).startOf('day').toDate();
var end = moment(value).endOf('day').toDate();
if (filter.operator === 'gt') {
filters[path] = { $gt: end };
} else if (filter.operator === 'lt') {
filters[path] = { $lt: start };
} else {
filters[path] = { $lte: end, $gte: start };
}
}
}
break;
case 'text':
case 'textarea':
case 'html':
case 'email':
case 'url':
case 'key':
if (filter.exact) {
if (value) {
cond = new RegExp('^' + utils.escapeRegExp(value) + '$', 'i');
filters[path] = filter.inverse ? { $not: cond } : cond;
} else {
if (filter.inverse) {
filters[path] = { $nin: ['', null] };
} else {
filters[path] = { $in: ['', null] };
}
}
} else if (value) {
cond = new RegExp(utils.escapeRegExp(value), 'i');
filters[path] = filter.inverse ? { $not: cond } : cond;
}
break;
}
});
}
debug('Applying filters to list \'' + list.key + '\':', filters);
return filters;
}
|
Gets filters for a Mongoose query that will search for the provided string,
based on the searchFields List option.
Also accepts a filters object from `processFilters()`, any of which may
override the search string.
NOTE: This function is deprecated in favor of List.prototype.addSearchToQuery
and will be removed in a later version.
Example:
list.getSearchFilters('jed') // returns { name: /jed/i }
@param {String} query
@param {Object} additional filters
|
getSearchFilters
|
javascript
|
keystonejs/keystone-classic
|
lib/list/getSearchFilters.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/getSearchFilters.js
|
MIT
|
function getUniqueValue (path, generator, limit, callback) {
var model = this.model;
var count = 0;
var value;
if (typeof limit === 'function') {
callback = limit;
limit = 10;
}
if (Array.isArray(generator)) {
var fn = generator[0];
var args = generator.slice(1);
generator = function () {
return fn.apply(this, args);
};
}
var check = function () {
if (count++ > 10) {
return callback(undefined, undefined);
}
value = generator();
model.count().where(path, value).exec(function (err, matches) {
if (err) return callback(err);
if (matches) return check();
callback(undefined, value);
});
};
check();
}
|
Gets a unique value from a generator method by checking for documents with the same value.
To avoid infinite loops when a unique value cannot be found, it will bail and pass back an
undefined value after 10 attemptes.
WARNING: Because there will always be a small amount of time between checking for an
existing value and saving a document, race conditions can occur and it is possible that
another document has the 'unique' value assigned at the same time.
Because of this, if true uniqueness is required, you should also create a unique index on
the database path, and handle duplicate errors thrown on save.
@param {String} path to check for uniqueness
@param {Function} generator method to call to generate a new value
@param {Number} the maximum number of attempts (optional, defaults to 10)
@param {Function} callback(err, uniqueValue)
|
getUniqueValue
|
javascript
|
keystonejs/keystone-classic
|
lib/list/getUniqueValue.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/getUniqueValue.js
|
MIT
|
check = function () {
if (count++ > 10) {
return callback(undefined, undefined);
}
value = generator();
model.count().where(path, value).exec(function (err, matches) {
if (err) return callback(err);
if (matches) return check();
callback(undefined, value);
});
}
|
Gets a unique value from a generator method by checking for documents with the same value.
To avoid infinite loops when a unique value cannot be found, it will bail and pass back an
undefined value after 10 attemptes.
WARNING: Because there will always be a small amount of time between checking for an
existing value and saving a document, race conditions can occur and it is possible that
another document has the 'unique' value assigned at the same time.
Because of this, if true uniqueness is required, you should also create a unique index on
the database path, and handle duplicate errors thrown on save.
@param {String} path to check for uniqueness
@param {Function} generator method to call to generate a new value
@param {Number} the maximum number of attempts (optional, defaults to 10)
@param {Function} callback(err, uniqueValue)
|
check
|
javascript
|
keystonejs/keystone-classic
|
lib/list/getUniqueValue.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/getUniqueValue.js
|
MIT
|
function isReserved (path) {
return reservedPaths.indexOf(path) >= 0;
}
|
Check whether or not a `path` is a reserved path. This restricts the use
of `Object.prototype` method keys as well as internal mongo paths.
|
isReserved
|
javascript
|
keystonejs/keystone-classic
|
lib/list/isReserved.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/isReserved.js
|
MIT
|
function map (field, path) {
if (path) {
this.mappings[field] = path;
}
return this.mappings[field];
}
|
Maps a built-in field (e.g. name) to a specific path
|
map
|
javascript
|
keystonejs/keystone-classic
|
lib/list/map.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/map.js
|
MIT
|
function paginate (options, callback) {
var list = this;
var model = this.model;
options = options || {};
var query = model.find(options.filters, options.optionalExpression);
var countQuery = model.find(options.filters);
query._original_exec = query.exec;
query._original_sort = query.sort;
query._original_select = query.select;
var currentPage = Number(options.page) || 1;
var resultsPerPage = Number(options.perPage) || 50;
var maxPages = Number(options.maxPages) || 10;
var skip = (currentPage - 1) * resultsPerPage;
list.pagination = { maxPages: maxPages };
// as of mongoose 3.7.x, we need to defer sorting and field selection
// until after the count has been executed
query.select = function () {
options.select = arguments[0];
return query;
};
query.sort = function () {
options.sort = arguments[0];
return query;
};
query.exec = function (callback) {
countQuery.count(function (err, count) {
if (err) return callback(err);
query.find().limit(resultsPerPage).skip(skip);
// apply the select and sort options before calling exec
if (options.select) {
query._original_select(options.select);
}
if (options.sort) {
query._original_sort(options.sort);
}
query._original_exec(function (err, results) {
if (err) return callback(err);
var totalPages = Math.ceil(count / resultsPerPage);
var rtn = {
total: count,
results: results,
currentPage: currentPage,
totalPages: totalPages,
pages: [],
previous: (currentPage > 1) ? (currentPage - 1) : false,
next: (currentPage < totalPages) ? (currentPage + 1) : false,
first: skip + 1,
last: skip + results.length,
};
list.getPages(rtn, maxPages);
callback(err, rtn);
});
});
};
if (callback) {
return query(callback);
} else {
return query;
}
}
|
Gets a special Query object that will paginate documents in the list
Example:
list.paginate({
page: 1,
perPage: 100,
maxPages: 10
}).exec(function(err, results) {
// do something
});
@param {Object} options
@param {Function} callback (optional)
|
paginate
|
javascript
|
keystonejs/keystone-classic
|
lib/list/paginate.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/paginate.js
|
MIT
|
function processFilters (q) {
var list = this;
var filters = {};
queryfilterlib.QueryFilters.create(q).getFilters().forEach(function (filter) {
filter.path = filter.key; // alias for b/c
filter.field = list.fields[filter.key];
filters[filter.path] = filter;
});
return filters;
}
|
Processes a filter string into a filters object
NOTE: This function is deprecated in favor of List.prototype.addFiltersToQuery
and will be removed in a later version.
@param {String} filters
|
processFilters
|
javascript
|
keystonejs/keystone-classic
|
lib/list/processFilters.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/processFilters.js
|
MIT
|
function register () {
var keystone = this.keystone;
var list = this;
/* Handle deprecated options */
if (this.schema.methods.toCSV) {
console.warn(this.key + ' Warning: List.schema.methods.toCSV support has been removed from KeystoneJS.\nPlease use getCSVData instead (see the 0.3 -> 4.0 Upgrade Guide)\n');
}
/* Apply Plugins */
if (this.get('sortable')) {
schemaPlugins.sortable.apply(this);
}
if (this.get('autokey')) {
schemaPlugins.autokey.apply(this);
}
if (this.get('track')) {
schemaPlugins.track.apply(this);
}
if (this.get('history')) {
schemaPlugins.history.apply(this);
}
this.schema.virtual('list').get(function () {
return list;
});
/* Add common methods to the schema */
if (Object.keys(this.relationships).length) {
this.schema.methods.getRelated = schemaPlugins.methods.getRelated;
this.schema.methods.populateRelated = schemaPlugins.methods.populateRelated;
if (!this.schema.options.toObject) this.schema.options.toObject = {};
this.schema.options.toObject.transform = schemaPlugins.options.transform;
}
this.schema.virtual('_').get(function () {
if (!this.__methods) {
this.__methods = utils.bindMethods(list.underscoreMethods, this);
}
return this.__methods;
});
this.schema.method('getUpdateHandler', function (req, res, ops) {
return new UpdateHandler(list, this, req, res, ops);
});
/* Apply list inheritance */
if (this.get('inherits')) {
this.model = this.get('inherits').model.discriminator(this.key, this.schema);
} else {
this.model = keystone.mongoose.model(this.key, this.schema);
}
/* Setup search text index */
if (this.options.searchUsesTextIndex && !this.declaresTextIndex()) {
// If the list is configured to use a text index for search and the list
// doesn't explicitly define one, create (or update) one of our own
this.ensureTextIndex(function () {
debug('this.ensureTextIndex() done for \'' + list.key + '\'');
});
}
/* Register the list and its field types on the Keystone instance */
keystone.lists[this.key] = this;
keystone.paths[this.path] = this.key;
assign(keystone.fieldTypes, this.fieldTypes);
/* Add listeners for model events */
// see http://mongoosejs.com/docs/api.html#model_Model
this.model.on('index', function (err) {
if (err) console.error('Mongoose model \'index\' event fired on \'' + list.key + '\' with error:\n', err.message, err.stack);
});
this.model.on('index-single-start', function (index) {
debug('Mongoose model \'index-single-start\' event fired on \'' + list.key + '\' for index:\n', index);
});
this.model.on('index-single-done', function (err, index) {
if (err) console.error('Mongoose model \'index-single-done\' event fired on \'' + list.key + '\' for index:\n', index, '\nWith error:\n', err.message, err.stack);
else debug('Mongoose model \'index-single-done\' event fired on \'' + list.key + '\' for index:\n', index);
});
this.model.on('error', function (err) {
if (err) console.error('Mongoose model \'error\' event fired on \'' + list.key + '\' with error:\n', err.message, err.stack);
});
return this;
}
|
Registers the Schema with Mongoose, and the List with Keystone
Also adds default fields and virtuals to the schema for the list
|
register
|
javascript
|
keystonejs/keystone-classic
|
lib/list/register.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/register.js
|
MIT
|
function relationship (def) {
var keystone = this.keystone;
if (arguments.length > 1) {
for (var i = 0; i < arguments.length; i++) {
this.relationship(arguments[i]);
}
return this;
}
if (typeof def === 'string') {
def = { ref: def };
}
if (!def.ref) {
throw new Error('List Relationships must be specified with an object containing ref (' + this.key + ')');
}
if (!def.refPath) {
def.refPath = utils.downcase(this.key);
}
if (!def.path) {
def.path = utils.keyToProperty(def.ref, true);
}
Object.defineProperty(def, 'refList', {
get: function () {
return keystone.list(def.ref);
},
});
Object.defineProperty(def, 'isValid', {
get: function () {
return keystone.list(def.ref) ? true : false;
},
});
this.relationships[def.path] = def;
return this;
}
|
Registers relationships to this list defined on others
|
relationship
|
javascript
|
keystonejs/keystone-classic
|
lib/list/relationship.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/relationship.js
|
MIT
|
function selectColumns (q, cols) {
// Populate relationship columns
var select = [];
var populate = {};
var path;
cols.forEach(function (col) {
select.push(col.path);
if (col.populate) {
if (!populate[col.populate.path]) {
populate[col.populate.path] = [];
}
populate[col.populate.path].push(col.populate.subpath);
}
});
q.select(select.join(' '));
for (path in populate) {
if (populate.hasOwnProperty(path)) {
q.populate(path, populate[path].join(' '));
}
}
}
|
Specified select and populate options for a query based the provided columns.
@param {Query} query
@param {Array} columns
|
selectColumns
|
javascript
|
keystonejs/keystone-classic
|
lib/list/selectColumns.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/selectColumns.js
|
MIT
|
function set (key, value) {
if (arguments.length === 1) {
return this.options[key];
}
this.options[key] = value;
return value;
}
|
Gets and Sets list options. Aliased as .get()
Example:
list.set('test') // returns the 'test' value
list.set('test', value) // sets the 'test' option to `value`
|
set
|
javascript
|
keystonejs/keystone-classic
|
lib/list/set.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/set.js
|
MIT
|
function underscoreMethod (path, fn) {
var target = this.underscoreMethods;
path = path.split('.');
var last = path.pop();
path.forEach(function (part) {
if (!target[part]) target[part] = {};
target = target[part];
});
target[last] = fn;
return this;
}
|
Adds a method to the underscoreMethods collection on the list, which is then
added to the schema before the list is registered with mongoose.
|
underscoreMethod
|
javascript
|
keystonejs/keystone-classic
|
lib/list/underscoreMethod.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/list/underscoreMethod.js
|
MIT
|
function Storage (options) {
// we're going to mutate options so get a clean copy of it
options = assign({}, options);
var AdapterType = options.adapter;
delete options.adapter;
if (typeof AdapterType !== 'function') {
throw new Error('Invalid Storage Adapter\n'
+ 'The storage adapter specified is not a function. Did you '
+ 'require the right package?\n');
}
debug('Initialising Storage with adapter ' + AdapterType.name);
// ensure the adapter compatibilityLevel of the adapter matches
if (AdapterType.compatibilityLevel !== ADAPTER_COMPATIBILITY_LEVEL) {
throw new Error('Incompatible Storage Adapter\n'
+ 'The storage adapter specified (' + AdapterType.name + ') '
+ 'does not match the compatibility level required for this '
+ 'version of Keystone.\n');
}
// assign ensures the default schema constant isn't exposed as a property
var schemaFields = assign({}, SCHEMA_FIELD_DEFAULTS, AdapterType.SCHEMA_FIELD_DEFAULTS, options.schema);
delete options.schema;
// Copy requested fields into local schema.
var schema = this.schema = {};
for (var path in schemaFields) {
if (!schemaFields[path]) continue;
var type = AdapterType.SCHEMA_TYPES[path] || SCHEMA_TYPES[path];
if (!type) throw Error('Unknown type for requested schema field ' + path);
schema[path] = type;
}
// ensure Storage schema features are supported by the Adapter
if (schema.url && typeof AdapterType.prototype.getFileURL !== 'function') {
throw Error('URL schema field is not supported by the ' + AdapterType.name + ' adapter');
}
// create the adapter
this.adapter = new AdapterType(options, schema);
}
|
# Storage Prototype
Creates a new Keystone Storage instance, and validates and initialises the
specified adapter. Storage schema is configured from the adapter or default.
|
Storage
|
javascript
|
keystonejs/keystone-classic
|
lib/storage/index.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/storage/index.js
|
MIT
|
function getSize (file, callback) {
if (file.size) return callback(null, file.size);
fs.stat(file.path, function (err, stats) {
if (!stats.isFile()) {
return callback(Error(file.path + ' is not a file'));
}
callback(err, stats ? stats.size : null);
});
}
|
# Storage Prototype
Creates a new Keystone Storage instance, and validates and initialises the
specified adapter. Storage schema is configured from the adapter or default.
|
getSize
|
javascript
|
keystonejs/keystone-classic
|
lib/storage/index.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/storage/index.js
|
MIT
|
function normalizeFile (file, schema, callback) {
// Detect required information if it wasn't provided by inspecting the
// file stored at file.path
if (schema.mimetype && !file.mimetype) file.mimetype = mime(file.path);
if (!file.originalname) {
file.originalname = file.name
|| (file.path) ? path.parse(file.path).base : 'unnamedfile';
}
if (schema.size && !file.size) {
getSize(file, function (err, size) {
if (err) return callback(err);
file.size = size;
callback(null, file);
});
} else callback(null, file);
}
|
# Storage Prototype
Creates a new Keystone Storage instance, and validates and initialises the
specified adapter. Storage schema is configured from the adapter or default.
|
normalizeFile
|
javascript
|
keystonejs/keystone-classic
|
lib/storage/index.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/storage/index.js
|
MIT
|
function ready (err) {
callback(err, message);
}
|
Configures and starts express server in SSL.
Events are fired during initialisation to allow customisation, including:
- onHttpsServerCreated
consumed by lib/core/start.js
@api private
|
ready
|
javascript
|
keystonejs/keystone-classic
|
server/startSecureServer.js
|
https://github.com/keystonejs/keystone-classic/blob/master/server/startSecureServer.js
|
MIT
|
function kebabify (string) {
return string
.split('/')
.map(s => kebabCase(s))
.join('/');
}
|
Implement Gatsby's Node APIs in this file.
See: https://www.gatsbyjs.org/docs/node-apis/
|
kebabify
|
javascript
|
keystonejs/keystone-classic
|
website/gatsby-node.js
|
https://github.com/keystonejs/keystone-classic/blob/master/website/gatsby-node.js
|
MIT
|
set(key, value) {
throw new Error('Set is not overridden!');
}
|
@param {!string} key
@param {!string} value
@return {!Promise}
|
set
|
javascript
|
yujiosaka/headless-chrome-crawler
|
cache/base.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/cache/base.js
|
MIT
|
enqueue(key, value, priority) {
throw new Error('Enqueue is not overridden!');
}
|
@param {!string} key
@param {!string} value
@param {!number=} priority
@return {!Promise}
|
enqueue
|
javascript
|
yujiosaka/headless-chrome-crawler
|
cache/base.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/cache/base.js
|
MIT
|
size(key) {
throw new Error('Size is not overridden!');
}
|
@param {!string} key
@return {!Promise<!number>}
|
size
|
javascript
|
yujiosaka/headless-chrome-crawler
|
cache/base.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/cache/base.js
|
MIT
|
get(key) {
return new Promise((resolve, reject) => {
this._client.get(key, (error, json) => {
if (error) {
reject(error);
return;
}
try {
const value = JSON.parse(json || null);
resolve(value);
} catch (_error) {
reject(_error);
}
});
});
}
|
@param {!string} key
@return {!Promise}
@override
|
get
|
javascript
|
yujiosaka/headless-chrome-crawler
|
cache/redis.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/cache/redis.js
|
MIT
|
set(key, value) {
return new Promise((resolve, reject) => {
let json;
try {
json = JSON.stringify(value);
} catch (error) {
reject(error);
return;
}
this._client.set(key, json, error => {
if (error) {
reject(error);
return;
}
if (!this._settings.expire) {
resolve();
return;
}
this._client.expire(key, this._settings.expire, _error => {
if (_error) {
reject(_error);
return;
}
resolve();
});
});
});
}
|
@param {!string} key
@param {!string} value
@return {!Promise}
@override
|
set
|
javascript
|
yujiosaka/headless-chrome-crawler
|
cache/redis.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/cache/redis.js
|
MIT
|
enqueue(key, value, priority = 1) {
return new Promise((resolve, reject) => {
let json;
try {
json = JSON.stringify(value);
} catch (error) {
reject(error);
return;
}
this._client.zadd(key, priority, json, error => {
if (error) {
reject(error);
return;
}
if (!this._settings.expire) {
resolve();
return;
}
this._client.expire(key, this._settings.expire, _error => {
if (_error) {
reject(_error);
return;
}
resolve();
});
});
});
}
|
@param {!string} key
@param {!string} value
@param {!number=} priority
@return {!Promise}
@override
|
enqueue
|
javascript
|
yujiosaka/headless-chrome-crawler
|
cache/redis.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/cache/redis.js
|
MIT
|
dequeue(key) {
return new Promise((resolve, reject) => {
this._client.eval(DEQUEUE_SCRIPT, 1, key, (error, json) => {
if (error) {
reject(error);
return;
}
try {
const value = JSON.parse(json || null);
resolve(value);
} catch (_error) {
reject(_error);
}
});
});
}
|
@param {!string} key
@return {!Promise}
@override
|
dequeue
|
javascript
|
yujiosaka/headless-chrome-crawler
|
cache/redis.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/cache/redis.js
|
MIT
|
size(key) {
return new Promise((resolve, reject) => {
this._client.zcount(key, '-inf', 'inf', (error, size) => {
if (error) {
reject(error);
return;
}
resolve(size || 0);
});
});
}
|
@param {!string} key
@return {!Promise<!number>}
@override
|
size
|
javascript
|
yujiosaka/headless-chrome-crawler
|
cache/redis.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/cache/redis.js
|
MIT
|
remove(key) {
return new Promise((resolve, reject) => {
this._client.del(key, error => {
if (error) {
reject(error);
return;
}
resolve();
});
});
}
|
@param {!string} key
@return {!Promise}
@override
|
remove
|
javascript
|
yujiosaka/headless-chrome-crawler
|
cache/redis.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/cache/redis.js
|
MIT
|
get(key) {
return Promise.resolve(this._storage.get(key) || null);
}
|
@param {!string} key
@return {!Promise}
@override
|
get
|
javascript
|
yujiosaka/headless-chrome-crawler
|
cache/session.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/cache/session.js
|
MIT
|
set(key, value) {
this._storage.set(key, value);
return Promise.resolve();
}
|
@param {!string} key
@param {!string} value
@return {!Promise}
@override
|
set
|
javascript
|
yujiosaka/headless-chrome-crawler
|
cache/session.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/cache/session.js
|
MIT
|
enqueue(key, value, priority) {
const queue = this._storage.get(key) || [];
const item = { value, priority };
if (queue.length && queue[queue.length - 1].priority >= priority) {
queue.push(item);
this._storage.set(key, queue);
return Promise.resolve();
}
const index = lowerBound(queue, item, (a, b) => b.priority - a.priority);
queue.splice(index, 0, item);
this._storage.set(key, queue);
return Promise.resolve();
}
|
@param {!string} key
@param {!string} value
@param {!number=} priority
@return {!Promise}
@override
|
enqueue
|
javascript
|
yujiosaka/headless-chrome-crawler
|
cache/session.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/cache/session.js
|
MIT
|
dequeue(key) {
const queue = this._storage.get(key) || [];
this._storage.set(key, queue);
const item = queue.shift();
if (!item) return Promise.resolve(null);
return Promise.resolve(item.value);
}
|
@param {!string} key
@return {!Promise}
@override
|
dequeue
|
javascript
|
yujiosaka/headless-chrome-crawler
|
cache/session.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/cache/session.js
|
MIT
|
size(key) {
const queue = this._storage.get(key);
if (!queue) return Promise.resolve(0);
return Promise.resolve(queue.length);
}
|
@param {!string} key
@return {!Promise<!number>}
@override
|
size
|
javascript
|
yujiosaka/headless-chrome-crawler
|
cache/session.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/cache/session.js
|
MIT
|
remove(key) {
this._storage.delete(key);
return Promise.resolve();
}
|
@param {!string} key
@return {!Promise}
@override
|
remove
|
javascript
|
yujiosaka/headless-chrome-crawler
|
cache/session.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/cache/session.js
|
MIT
|
emitAsync(event, ...args) {
const promises = [];
this.listeners(event).forEach(listener => {
promises.push(listener(...args));
});
return Promise.all(promises);
}
|
@param {!string} event
@param {...*} args
@return {!Promise}
|
emitAsync
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/async-events.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/async-events.js
|
MIT
|
constructor(page, options, depth, previousUrl) {
this._page = page;
this._options = options;
this._depth = depth;
this._previousUrl = previousUrl;
}
|
@param {!Puppeteer.Page} page
@param {!Object} options
@param {!number} depth
@param {string} previousUrl
|
constructor
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/crawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/crawler.js
|
MIT
|
async _handleDialog(dialog) {
debugDialog(`${dialog.type()} ${dialog.message()} at ${this._options.url}`);
await dialog.dismiss();
}
|
@param {!Puppeteer.Dialog} dialog
@return {!Promise}
@private
|
_handleDialog
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/crawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/crawler.js
|
MIT
|
async _collectLinks(baseUrl) {
const links = [];
await this._page.exposeFunction('pushToLinks', link => {
const _link = resolveUrl(link, baseUrl);
if (_link) links.push(_link);
});
await this._page.evaluate(() => {
function findLinks(document) {
document.querySelectorAll('a[href]')
.forEach(link => {
// @ts-ignore
window.pushToLinks(link.href);
});
document.querySelectorAll('iframe,frame')
.forEach(frame => {
try {
findLinks(frame.contentDocument);
} catch (e) {
console.warn(e.message);
// @ts-ignore
if (frame.src) window.pushToLinks(frame.src);
}
});
}
findLinks(window.document);
});
return uniq(links);
}
|
@param {!string} baseUrl
@return {!Promise<!Array<!string>>}
@private
|
_collectLinks
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/crawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/crawler.js
|
MIT
|
function findLinks(document) {
document.querySelectorAll('a[href]')
.forEach(link => {
// @ts-ignore
window.pushToLinks(link.href);
});
document.querySelectorAll('iframe,frame')
.forEach(frame => {
try {
findLinks(frame.contentDocument);
} catch (e) {
console.warn(e.message);
// @ts-ignore
if (frame.src) window.pushToLinks(frame.src);
}
});
}
|
@param {!string} baseUrl
@return {!Promise<!Array<!string>>}
@private
|
findLinks
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/crawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/crawler.js
|
MIT
|
_reduceRequest(request) {
return reduce(REQUEST_FIELDS, (memo, field) => {
memo[field] = request[field]();
return memo;
}, {});
}
|
@param {!Puppeteer.Request} request
@return {!Object}
@private
|
_reduceRequest
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/crawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/crawler.js
|
MIT
|
_reduceResponse(response) {
return reduce(RESPONSE_FIELDS, (memo, field) => {
memo[field] = response[field]();
return memo;
}, {});
}
|
@param {!Puppeteer.Response} response
@return {!Object}
@private
|
_reduceResponse
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/crawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/crawler.js
|
MIT
|
_getRedirectChain(response) {
return map(response.request().redirectChain(), this._reduceRequest);
}
|
@param {!Puppeteer.Response} response
@return {!Array<!Object>}
@private
|
_getRedirectChain
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/crawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/crawler.js
|
MIT
|
static async connect(options) {
const browser = await Puppeteer.connect(pick(options, CONNECT_OPTIONS));
const crawler = new HCCrawler(browser, omit(options, CONNECT_OPTIONS));
await crawler.init();
return crawler;
}
|
@param {!Object=} options
@return {!Promise<!HCCrawler>}
|
connect
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
static async launch(options) {
const browser = await Puppeteer.launch(pick(options, LAUNCH_OPTIONS));
const crawler = new HCCrawler(browser, omit(options, LAUNCH_OPTIONS));
await crawler.init();
return crawler;
}
|
@param {!Object=} options
@return {!Promise<!HCCrawler>}
|
launch
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
constructor(browser, options) {
super();
this._browser = browser;
this._options = extend({
maxDepth: 1,
maxConcurrency: 10,
maxRequest: 0,
priority: 0,
delay: 0,
retryCount: 3,
retryDelay: 10000,
timeout: 30000,
jQuery: true,
browserCache: true,
persistCache: false,
skipDuplicates: true,
depthPriority: true,
obeyRobotsTxt: true,
followSitemapXml: false,
skipRequestedRedirect: false,
cookies: null,
screenshot: null,
viewport: null,
}, options);
this._cache = options.cache || new SessionCache();
this._queue = new PriorityQueue({
maxConcurrency: this._options.maxConcurrency,
cache: this._cache,
});
this._exporter = options.exporter || null;
this._requestedCount = 0;
this._preRequest = options.preRequest || null;
this._onSuccess = options.onSuccess || null;
this._onError = options.onError || null;
this._customCrawl = options.customCrawl || null;
this._exportHeader();
this._queue.on('pull', (_options, depth, previousUrl) => this._startRequest(_options, depth, previousUrl));
this._browser.on('disconnected', () => void this.emit(HCCrawler.Events.Disconnected));
}
|
@param {!Puppeteer.Browser} browser
@param {!Object} options
|
constructor
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
async queue(options) {
await Promise.all(map(isArray(options) ? options : [options], async _options => {
const queueOptions = isString(_options) ? { url: _options } : _options;
each(CONSTRUCTOR_OPTIONS, option => {
if (queueOptions && queueOptions[option]) throw new Error(`Overriding ${option} is not allowed!`);
});
const mergedOptions = extend({}, this._options, queueOptions);
if (mergedOptions.evaluatePage) mergedOptions.evaluatePage = `(${mergedOptions.evaluatePage})()`;
if (!mergedOptions.url) throw new Error('Url must be defined!');
if (mergedOptions.device && !includes(deviceNames, mergedOptions.device)) throw new Error('Specified device is not supported!');
if (mergedOptions.delay > 0 && mergedOptions.maxConcurrency !== 1) throw new Error('Max concurrency must be 1 when delay is set!');
mergedOptions.url = parse(mergedOptions.url).href;
await this._push(omit(mergedOptions, CONSTRUCTOR_OPTIONS), 1, null);
}));
}
|
@param {?Object|?Array<!string>|?string} options
@return {!Promise}
|
queue
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
async _push(options, depth, previousUrl) {
let { priority } = options;
if (!priority && options.depthPriority) priority = depth;
await this._queue.push(options, depth, previousUrl, priority);
}
|
@param {!Object} options
@param {!number} depth
@param {string} previousUrl
@return {!Promise}
|
_push
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
async _startRequest(options, depth, previousUrl) {
const skip = await this._skipRequest(options);
if (skip) {
this.emit(HCCrawler.Events.RequestSkipped, options);
await this._markRequested(options);
return;
}
const allowed = await this._checkAllowedRobots(options, depth, previousUrl);
if (!allowed) {
this.emit(HCCrawler.Events.RequestDisallowed, options);
await this._markRequested(options);
return;
}
await this._followSitemap(options, depth, previousUrl);
const links = await this._request(options, depth, previousUrl);
this._checkRequestCount();
await this._followLinks(links, options, depth);
await delay(options.delay);
}
|
@param {!Object} options
@param {!number} depth
@param {string} previousUrl
@return {!Promise}
@private
|
_startRequest
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
async _skipRequest(options) {
const allowedDomain = this._checkAllowedDomains(options);
if (!allowedDomain) return true;
const requested = await this._checkRequested(options);
if (requested) return true;
const shouldRequest = await this._shouldRequest(options);
if (!shouldRequest) return true;
return false;
}
|
@param {!Object} options
@return {!Promise<!boolean>}
@private
|
_skipRequest
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
async _request(options, depth, previousUrl, retryCount = 0) {
this.emit(HCCrawler.Events.RequestStarted, options);
const crawler = await this._newCrawler(options, depth, previousUrl);
try {
const res = await this._crawl(crawler);
await crawler.close();
this.emit(HCCrawler.Events.RequestFinished, options);
const requested = await this._checkRequestedRedirect(options, res.response);
await this._markRequested(options);
await this._markRequestedRedirects(options, res.redirectChain, res.response);
if (requested) return [];
this._exportLine(res);
await this._success(res);
return res.links;
} catch (error) {
await crawler.close();
extend(error, { options, depth, previousUrl });
if (retryCount >= options.retryCount) {
this.emit(HCCrawler.Events.RequestFailed, error);
await this._error(error);
return [];
}
this.emit(HCCrawler.Events.RequestRetried, options);
await delay(options.retryDelay);
return this._request(options, depth, previousUrl, retryCount + 1);
}
}
|
@param {!Object} options
@param {!number} depth
@param {string} previousUrl
@param {!number=} retryCount
@return {!Promise<!Array<!string>>}
@private
|
_request
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
async _checkAllowedRobots(options, depth, previousUrl) {
if (!options.obeyRobotsTxt) return true;
const robot = await this._getRobot(options, depth, previousUrl);
const userAgent = await this._getUserAgent(options);
return robot.isAllowed(options.url, userAgent);
}
|
@param {!Object} options
@param {!number} depth
@param {string} previousUrl
@return {!Promise<!boolean>}
@private
|
_checkAllowedRobots
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
async _followSitemap(options, depth, previousUrl) {
if (!options.followSitemapXml) return;
const robot = await this._getRobot(options, depth, previousUrl);
const sitemapUrls = robot.getSitemaps();
await Promise.resolve(map(sitemapUrls, async sitemapUrl => {
const sitemapXml = await this._getSitemapXml(sitemapUrl, options, depth, previousUrl);
const urls = getSitemapUrls(sitemapXml);
await Promise.all(map(urls, async url => {
await this._push(extend({}, options, { url }), depth, options.url);
}));
}));
}
|
@param {!Object} options
@param {!number} depth
@param {string} previousUrl
@return {!Promise}
@private
|
_followSitemap
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
async _getSitemapXml(sitemapUrl, options, depth, previousUrl) {
let sitemapXml = await this._cache.get(sitemapUrl);
if (!sitemapXml) {
try {
sitemapXml = await rp(sitemapUrl);
} catch (error) {
extend(error, { options, depth, previousUrl });
this.emit(HCCrawler.Events.SitemapXmlRequestFailed, error);
sitemapXml = EMPTY_TXT;
} finally {
await this._cache.set(sitemapUrl, '1');
}
}
return sitemapXml;
}
|
@param {!string} sitemapUrl
@param {!Object} options
@param {!number} depth
@param {string} previousUrl
@return {!Promise<!string>}
|
_getSitemapXml
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
async _getRobot(options, depth, previousUrl) {
const robotsUrl = getRobotsUrl(options.url);
let robotsTxt = await this._cache.get(robotsUrl);
if (!robotsTxt) {
try {
robotsTxt = await rp(robotsUrl);
} catch (error) {
extend(error, { options, depth, previousUrl });
this.emit(HCCrawler.Events.RobotsTxtRequestFailed, error);
robotsTxt = EMPTY_TXT;
} finally {
await this._cache.set(robotsUrl, robotsTxt);
}
}
return robotsParser(robotsUrl, robotsTxt);
}
|
@param {!Object} options
@param {!number} depth
@param {string} previousUrl
@return {!Promise}
@private
|
_getRobot
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
async _getUserAgent(options) {
if (options.userAgent) return options.userAgent;
if (devices[options.device]) return devices[options.device].userAgent;
return this.userAgent();
}
|
@param {!Object} options
@return {!Promise<!string>}
@private
|
_getUserAgent
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
_checkAllowedDomains(options) {
const { hostname } = parse(options.url);
if (options.deniedDomains && checkDomainMatch(options.deniedDomains, hostname)) return false;
if (options.allowedDomains && !checkDomainMatch(options.allowedDomains, hostname)) return false;
return true;
}
|
@param {!Object} options
@return {!boolean}
@private
|
_checkAllowedDomains
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
async _checkRequested(options) {
if (!options.skipDuplicates) return false;
const key = generateKey(options);
const value = await this._cache.get(key);
return !!value;
}
|
@param {!Object} options
@return {!Promise<!boolean>}
@private
|
_checkRequested
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
async _checkRequestedRedirect(options, response) {
if (!options.skipRequestedRedirect) return false;
const requested = await this._checkRequested(extend({}, options, { url: response.url }));
return requested;
}
|
@param {!Object} options
@param {!Object} response
@return {!Promise<!boolean>}
@private
|
_checkRequestedRedirect
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
async _markRequested(options) {
if (!options.skipDuplicates) return;
const key = generateKey(options);
await this._cache.set(key, '1');
}
|
@param {!Object} options
@return {!Promise}
@private
|
_markRequested
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
async _markRequestedRedirects(options, redirectChain, response) {
if (!options.skipRequestedRedirect) return;
await Promise.all(map(redirectChain, async request => {
await this._markRequested(extend({}, options, { url: request.url }));
}));
await this._markRequested(extend({}, options, { url: response.url }));
}
|
@param {!Object} options
@param {!Array<!Object>} redirectChain
@param {!Object} response
@return {!Promise}
@private
|
_markRequestedRedirects
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
async _shouldRequest(options) {
if (!this._preRequest) return true;
return this._preRequest(options);
}
|
@param {!Object} options
@return {!Promise<?boolean>}
@private
|
_shouldRequest
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
async _success(result) {
if (!this._onSuccess) return;
await this._onSuccess(result);
}
|
@param {!Object} result
@return {!Promise}
@private
|
_success
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
async _error(error) {
if (!this._onError) return;
await this._onError(error);
}
|
@param {!Error} error
@return {!Promise}
@private
|
_error
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
async _newCrawler(options, depth, previousUrl) {
const page = await this._browser.newPage();
return new Crawler(page, options, depth, previousUrl);
}
|
@param {!Object} options
@return {!Promise<!Crawler>}
@param {!number} depth
@param {string} previousUrl
@private
|
_newCrawler
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
async _crawl(crawler) {
if (!this._customCrawl) return crawler.crawl();
const crawl = () => crawler.crawl.call(crawler);
return this._customCrawl(crawler.page(), crawl);
}
|
@param {!Crawler} crawler
@return {!Promise<!Object>}
|
_crawl
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
async _followLinks(urls, options, depth) {
if (depth >= options.maxDepth) {
this.emit(HCCrawler.Events.MaxDepthReached);
return;
}
await Promise.all(map(urls, async url => {
const _options = extend({}, options, { url });
const skip = await this._skipRequest(_options);
if (skip) return;
await this._push(_options, depth + 1, options.url);
}));
}
|
@param {!Array<!string>} urls
@param {!Object} options
@param {!number} depth
@return {!Promise}
@private
|
_followLinks
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/hccrawler.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/hccrawler.js
|
MIT
|
static jsonStableReplacer(key, val) {
if (!isPlainObject(val)) return val;
return Object.keys(val).sort().reduce((obj, _key) => {
obj[_key] = val[_key];
return obj;
}, {});
}
|
@param {!string} key
@param {?*} val
@return {!Object}
|
jsonStableReplacer
|
javascript
|
yujiosaka/headless-chrome-crawler
|
lib/helper.js
|
https://github.com/yujiosaka/headless-chrome-crawler/blob/master/lib/helper.js
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.