Skip to content
Oskar Klintrot edited this page Oct 17, 2016 · 15 revisions

Home > Keystone API

###Keystone API Begin by creating a new Keystone instance
var keystone = require('keystone');

The Keystone instance is a global object.
You must call .init() or .connect(mongoose) in order to make use of the library.

###Method Reference The following is a list of methods available.

.connect([app, mongoose])

@param app {Express()} - Optional Custom Express instance
@param mongoose {Object} - Optional Custom Mongoose instance
@return this

Set the Mongoose and/or Express instance for Keystone to use. Order is not relevant.
Must be called before .init()

/* Express*/
var app = express(),
    keystone = require('keystone'),
    server,
    EventEmitter = require("events").EventEmitter;
	
var theEvents = new EventEmitter();

keystone.connect(app);

keystone.init({
    // config here
});

keystone.import('models');

theEvents.on('keystone ready',function() {
	var server = app.listen(3000);
	console.log('server started');
});

keystone.mount({
		onMount: function() {
        	theEvents.emit('keystone ready');
        }
});
/* Mongoose and Express*/
var mongoose = require('mongoose'),
    app = express(),
    keystone = require('keystone');

mongoose.connect('localhost', 'dbname');

keystone.connect(mongoose,app);

keystone.init({
    // config here
});

keystone.import('models');

keystone.start();
/* use without a webserver */
var mongoose = require('mongoose'),
    keystone = require('keystone');

keystone.connect(mongoose,app);

keystone.init({
    // config here
});

keystone.import('models');

mongoose.connect('localhost', 'dbname');

mongoose.connection.on('open', function() {
    // ready to do things, e.g.
    var User = keystone.list('User');
    new User.model().save();
});

.createItems(data[, options], callback)

@param data {Object} - Create item data
@param options {Object} - Optional Object of options
@param callback {Function} - Callback function on done or error
@return callback

Keystone's createItems function is a simple but powerful way to populate your database with data.

It can be used to create test fixtures or initialise your database with default content / users / etc.

There's also a shorthand syntax that can be used within update files; if you are using the auto updates feature, any file that exports a create object will automatically be wrapped and the data will be created.

createItems takes two passes at the data it is provided, first creating the items and retaining references by key (if provided) that can be used to populate relationships in the second pass. This makes it easy to create related data without asynchronous nesting (which for data creation sometimes ends up in knots).

The data argument should be an Object containing an Array for each List you want to populate. Each object in the array contains the data for a single item.

Each data property should match to a field path (or sub-field path) - all paths recognised by the UpdateHandler are usable.

A special property, __ref, can be set with a string value that is used to reference the item in relationships.

Relationship fields should contain either a string matching another item's __ref property, or (for many: true relationship fields) can contain an array of strings.

The options parameter can be used to override the default options.

var options = {
	verbose: false,
	strict: true
};

The callback(err, stats) function is passed the error (if there was one) and a stats object containing counts for each list of items that were created, and a special message property that can be parsed as Markdown or logged to the console.

// This example demonstrates complete usage of keystone.createItems,
// and how to use its callback to log the message to the console.
 
function(done) {
	
	keystone.createItems({
		
		User: [{
			'name.full': 'Jed Watson',
			email: 'jed@keystonejs.com',
			password: 'admin',
			isAdmin: true,
			__ref: 'jed'
		}],
		
		PostCategory: [{
			name: 'Keystone JS',
			__ref: 'keystone'
		}, {
			name: 'Node.js',
			__ref: 'node'
		}],
		
		Post: [{
			title: 'A draft post',
			author: 'jed',
			'content.brief': 'This is an example draft post.',
			categories: ['keystone', 'node']
		}, {
			title: 'A published post',
			state: 'published',
			author: 'jed',
			publishedDate: '2014-04-12',
			'content.brief': 'This post has been published!',
			categories: 'node'
		}]
		
	}, function(err, stats) {
		stats && console.log(stats.message);
		done(err);
	});
 
}
// This example demonstrates the shorthand syntax you can use to
// create items in a Keystone update script.
 
var keystone = require('keystone');
 
exports.create = {
	
	User: [{
		'name.full': 'Jed Watson',
		email: 'jed@keystonejs.com',
		password: 'admin',
		isAdmin: true,
		__ref: 'jed'
	}],
	
	PostCategory: [{
		name: 'Keystone JS',
		__ref: 'keystone'
	}, {
		name: 'Node.js',
		__ref: 'node'
	}],
	
	Post: [{
		title: 'A draft post',
		author: 'jed',
		'content.brief': 'This is an example draft post.',
		categories: ['keystone', 'node']
	}, {
		title: 'A published post',
		state: 'published',
		author: 'jed',
		publishedDate: '2014-04-12',
		'content.brief': 'This post has been published!',
		categories: 'node'
	}]
	
};

.expandPath(path)

@param key {String} - path
@return expandedPath

Expands a path to include moduleRoot if it is relative

var path = keystone.expandPath(keystone.get('views'));


.get(key)

@param key {String} - Key of the option you want to retrieve
@return value

Get a Keystone option/value pair.

var brand = keystone.get('brand');
// >> KeystoneJS

.getOrphanedLists()

@return nav

Retrieves orphaned lists (those not in a nav section)

var orphanLists = keystone.getOrphanedLists();

.getPath(key, defaultValue)

@param key {String} - Key of the option you want to retrieve
@param defaultValue {String} - Default value if key is not a valid option
@return path

Gets an expanded path option, expanded to include moduleRoot if it is relative.

var path = keystone.getPath('views', 'templates/views');

.importer(rel__dirname)

@param rel__dirname {String} - path
@return imported

Import all .js Modules in given path

var importRoutes = keystone.importer(__dirname);
 
var routes = {
    site: importRoutes('./site'),
    api: importRoutes('./api')
};

.init(options)

@param options {Object} - set the intital value of Keystone options
@return this

Initialize the Keystone options object. See Configuration Docs.

If a Mongoose or Express reference has not been created with .connect() they will be added.

keystone.init({
	'name': 'Keystone',
	'brand': 'KeystoneJS',
	'less': 'public',
	'static': 'public',
	'favicon': 'public/favicon.ico',
	'views': 'templates/views',
	'view engine': 'jade',
	'emails': 'templates/emails',
	'auto update': true,
	'session': true,
	'auth': true,
	'user model': 'User',
	'cookie secret': '=Hw1WfV6XlGW(w~K8=&5r%U2]EZ'
});

The minimum required to start a Keystone instance is the cookie secret option.


.list(arg)

@param arg {...String|Function} - current list key or new constructed List
@return list

Registers or retrieves a list. Used by List.register() to register a newly constructed List with Keystone.

var User = keystone.list('User');

User.model.find().exec(function(docs,err) {

});

*Note* - To retrieve a list that may return undefined you should use keystone.lists[key]. Using .list() will throw a ReferenceError if the arg is not a valid List or the key for a valid List


.mount([mountPath, parentApp, events])

@param mountPath {String} - Optional Folder to mount Keystone as a sub-app
@param parentApp {Express()} - Optional Express app
@param events {...Function|Object} - Optional Object with onMount event or Function to run once mounted
@return events.onMount()

You can use .mount() for custom Express setups. mountPath is an optional path to mount Keystone under. parentApp will be your Express app. The events parameter can be used to perform commands once Keystone has been mounted. If events is a function it will get mapped to {onMount: events}.

/* Mount Keystone as a sub-app */

var app = express(),
    keystone = require('keystone'),
    server,
    theEvents = require("events").EventEmitter;
    
...
set up your Express app and Keystone

you must call keystone.connect(app,mongoose) or keystone.init()
...

theEvents.on('keystone ready',function() {
	var server = app.listen(3000);
	console.log('server started');
});

keystone.mount('/content', app, {
    onMount: function() {
    	//put your app's static content and error handling middleware here and start your server
       theEvents.emit('keystone ready');
    }
});

.options(options)

@param options {Object} - An Object of key/value pairs to add to options.
@return keystone._options

Set multiple Keystone option/value pair.

keystone.options({test: value});

.populateRelated(docs, relationships, callback)

@param docs {Array} - Array of documents
@param relationships {Array} - Array of ref paths to populate
@param callback {Function} - Callback function on done or error
@return callback

Populate the related fields for an Array of docs.
*Note* - This is currently highly inefficient and should only be used in development, or for small data sets. There are lots of things that can be done to improve performance... later.

keystone.populateRelated(docs,['owner','memberOf'],function() {
    // docs are populated
});

.redirect(...params)

@param params {...String|Object} - String or Object of redirects
@return callback events

Adds one or more redirections (urls that are redirected when no matching routes are found, before treating the request as a 404)

keystone.redirect('/old-route', 'new-route');

keystone.redirect({
    '/old-route': 'new-route'
});

.routes(app)

@param app {Express()} - Express app instance
@return this

Adds bindings for the keystone routes

var app = express();
app.use(...); // middlewareroutes, routes, etc. should come before keystone is mounted / started
keystone.routes(app);

.set(key, value)

@param key {String} - Key of the option you want to set
@param value {...String|Object|Function|Array} - Can be any valid Object value
@return this

Set a Keystone option/value pair.

keystone.set('mongo','mongodb://localhost/keystone');

keystone.set('custom key',{key1:'key1'});

.start([events])

@param events {...Function|Object} - Function or Object of events
@return callback events

Start the Keystone server. You can work with the events in the example.

keystone.start({
    onMount: function() {

    },
    onStart: function() {
    
    },
    onHttpServerCreated: function() {

    },
    onHttpsServerCreated: function() {

    }
});

.static(app)

@param app {Express()} - Express App
@return this

Adds bindings for keystone static resources.
Can be included before other middleware (e.g. session management, logging, etc) for reduced overhead.

var app = express();
keystone.static(app);

.wrapHTMLError(title, [err])

@param title {String} - Error title
@param err {String} - Optional Error message
@return html

Wraps an error in simple HTML to be sent as a response to the browser

var html = keystone.wrapHTMLError('Credential Error','Please <a href="/keystone/signin">login</a> to view this page');

Constructor Reference

The following classes are available to call

###Email new keystone.Email

###List new keystone.List

###View new keystone.View

.on(on)

@param on {Function|Object|String} - Method to be executed in parallel to the init, action or render queue.
@return this

Adds a method (or array of methods) to be executed in parallel to the init, action or render queue.

view.on(function() {
    var thing = true;
    return thing;
  },
  function(next) {
    console.log('thing is true!');
    next();
  }
);

.query(key, query, options)

@param key {Array} - Keys can be nested paths, containing objects will be created as required.
@param query {Object} - Mongoose query
@param options {Object} - Options
@return chain - QueryCallbacks

Queues a mongoose query for execution before the view is rendered. The results of the query are set in locals[key]. Keys can be nested paths, containing objects will be created as required. The third argument then can be a method to call after the query is completed like function(err, results, callback), or a populatedRelated definition (string or array).

view.query('books', keystone.list('Book').model.find());

.render(renderFn, locals, callback)

@param renderFn {Function|String} - Render function
@param locals {Object} - Locals
@param callback {Function} - Render callback
@return undefined

Executes the current queue of init and action methods in series, and then executes the render function. If renderFn is a string, it is provided to res.render. It is expected that most init stacks require processing in series, but it is safe to execute actions in parallel. If there are several init methods that should be run in parallel, queue them as an array, e.g. view.on('init', [first, second]).