Project configuration options can be added to the kanso.json
file in your project directory.
{
"name": "myblog",
"load": "lib/app",
"modules": "lib",
"templates": "templates",
"attachments": "static"
}
The format of the loaded module (usually lib/app.js, depending on the "load" setting in kanso.json) follows the format of a CouchDB design doc. Any exported property of this module will be added to the design doc generated for your app.
Kanso will occasionally extend the default design doc API by adding some additional properties which have a special meaning.
The 'init' property is expected to be a function, and will be called on the initial page load, once the document is ready and the commonjs environment is available.
This property is optional and can be safely omitted. If you want to progressively enhance a fallback page returned by CouchDB on the first hit, or initialize some application state, this is the place to do it.
exports.init = function () {
alert('initializing app');
};
The 'types' property is used by the admin app to find types to show in the applications types list. It is also assumed to be the location of any custom types by the skeleton app's validation function.
It's a good idea to export your type definitions on this property to make them easy to re-use and compatible with the admin app.
exports.types = {
example: new Type('example', {
fields: {
title: fields.string(),
message: fields.string()
}
})
};
The 'sessionChange' property is expected to be a function and is called whenever a change to the user's session is detected (usually after calling login or logout from the session module).
Documentation for the builtin CommonJS modules distributed as part of
Kanso. All modules in this section can be used in your own code by doing:
require('kanso/<name>')
.
Functions related to the reading and manipulation of cookies.
Read cookies currently stored in the browser, returning an object keyed by cookie name.
Reads browser cookies and returned the value of the named cookie.
name | String |
---|
Creates a string for storing a cookie on the browser.
req | Request Object |
---|---|
opt | Object |
Sets a cookie on the browser, for use client-side only.
req | Request Object |
---|---|
opt | Object |
Creates a Set-Cookie header on a response object.
req | Request Object |
---|---|
res | Response Object |
opt | Object |
The core module contains functions used by kanso to facilitate the running of your app. You shouldn't need to use any of the functions here directly unless you're messing with the internals of Kanso.
Called by kanso.js once the design doc has been loaded. You should not need to call this directly.
Extracts groups from a url, eg:
'/some/path' with pattern '/some/:name' -> {name: 'path'}
pattern | String |
---|---|
url | String |
Extracts a splat value from a rewrite pattern and matching URL.
pattern | String |
---|---|
url | String |
Attempts to match rewrite from patterns to a URL, returning the matching rewrite object if successful.
method | String |
---|---|
url | String |
Replace group names and splats in a string with the value of that group or splat, eg:
"/:name" with groups {name: 'test'} -> "/test"
val | String |
---|---|
groups | Object |
splat | String |
Creates a new request object from a url and matching rewrite object. Query parameters are automatically populated from rewrite pattern.
method | String |
---|---|
url | String |
data | Object |
match | Object |
callback | Function |
Fetches the relevant document and calls the named show function.
req | Object |
---|---|
name | String |
docid | String |
callback | Function |
Fetches the relevant document and calls the named update function.
req | Object |
---|---|
name | String |
docid | String |
callback | Function |
Creates a fake head object from view results for passing to a list function being run client-side.
data | Object |
---|
Fetches the relevant view and calls the named list function with the results.
req | Object |
---|---|
name | String |
view | String |
callback | Function |
Creates a request object for the url and runs appropriate show, list or update functions.
method | String |
---|---|
url | String |
data | Object |
Add a history entry for the given url, prefixed with the baseURL for the app.
method | String | |
---|---|---|
url | String | |
data | Object | (Optional) |
hash | String | (Optional) |
Gets the current app-level URL (without baseURL prefix).
Tests is two urls are of the same origin. Accepts parsed url objects or strings as arguments.
Converts a full url to an app-level url (without baseURL prefix). example: {baseURL}/some/path -> /some/path
p | String |
---|
Used to decide whether to handle a link or not. Should detect app vs. external urls.
url | String |
---|
Contains functions for querying and storing data in CouchDB.
Make a request, with some default settings and proper callback handling. Used behind-the-scenes by most other DB module functions.
options | Object |
---|---|
callback | Function |
Fetches a document from the database the app is running on. Results are passed to the callback, with the first argument of the callback reserved for any exceptions that occurred (node.js style).
id | String |
---|---|
q | Object |
callback | Function |
Saves a document to the database the app is running on. Results are passed to the callback, with the first argument of the callback reserved for any exceptions that occurred (node.js style).
doc | Object |
---|---|
callback | Function |
Deletes a document from the database the app is running on. Results are passed to the callback, with the first argument of the callback reserved for any exceptions that occurred (node.js style).
doc | Object |
---|---|
callback | Function |
Fetches a view from the database the app is running on. Results are passed to the callback, with the first argument of the callback reserved for any exceptions that occurred (node.js style).
view | String |
---|---|
q | Object |
callback | Function |
Get all documents (including design docs).
q | Object | (Optional |
---|---|---|
callback | Function |
Properly encodes query parameters to CouchDB views etc. Handle complex keys and other non-string parameters by passing through JSON.stringify. Returns a shallow-copied clone of the original query after complex values have been stringified.
query | Object |
---|
Returns a new UUID generated by CouchDB. Its possible to cache multiple UUIDs for later use, to avoid making too many requests.
cacheNum | Number | (Optional) Default: 1 |
---|---|---|
callback | Function |
The building blocks of Types and Forms, Fields help to validate and authorize changes to docuemnt values.
Field objects are used when constructing content types and forms.
options | Object | see below for available properties |
---|
omit_empty | Boolean | Whether to omit the field from a document when the field is empty |
---|---|---|
permissions | Object | A permissions check function or an object containing separate functions to run on create, edit and update operations. |
validators | Array | An array of validation functions (default: []) |
required | Boolean | Whether the field is required (default: true) |
Parses a raw value returning the correct JavaScript type for this field. This will usually be overridden by other field types.
raw |
---|
Test values to see if field is considered empty.
This function accepts the raw value even though by default it only checks the parsed value, so that other field types overridding this method have the raw data available.
value | The parsed value for the field |
---|---|
raw | The raw value for the field |
Run the field's validation functions against a value. Returns an array of validation errors, or an empty array if valid.
doc | Object |
---|---|
value | |
raw |
Check relevant field permissions to see if user is authorised to make changes. Returns an array of permissions errors, or an empty array if the changes are permissible.
newDoc | Object |
---|---|
oldDoc | Object |
newVal | |
oldVal | |
userCtx | Object |
Embedded objects represent a Type embedded within another Type or set of Fields. Its not a true field, but like the Field constructor it acts as a marker when walking through the sub-objects that make up a schema.
Exposes the same methods as Field objects.
options | Object | See below for available properties |
---|
type | Type Object | Required, the Type definition to embed |
---|---|---|
omit_empty | Boolean | Whether to omit the field from a document when the field is empty |
permissions | Object | A permissions check function or an object containing separate functions to run on create, edit and update operations. |
validators | Array | An array of validation functions (default: []) |
required | Boolean | Whether the field is required (default: true) |
EmbeddedList objects represent multiple instances of a Type embedded within another Type or set of Fields. Its not a true field, but like the Field constructor it acts as a marker when walking through the sub-objects that make up a schema.
Exposes the same methods as Field objects.
options | Object | See below for available properties |
---|
type | Type Object | Required, the Type definition to embed |
---|---|---|
omit_empty | Boolean | Whether to omit the field from a document when the field is empty |
permissions | Object | A permissions check function or an object containing separate functions to run on create, edit and update operations. |
validators | Array | An array of validation functions (default: []) |
required | Boolean | Whether the field is required (default: true) |
Detects embedded documents with missing _id properties and returns an array of Error objects for each occurence. Returns an empty array if all documents have a populated _id property.
list | Array |
---|
Detects embedded documents with duplicate _id properties and returns an array of Error objects for each occurence. Returns an empty array if all documents have a unique _id property.
list | Array |
---|
Creates a new string Field
options | Object | See the Field constructor for available options |
---|
Creates a new number Field
options | Object | See the Field constructor for available options |
---|
Creates a new boolean Field
options | Object | See the Field constructor for available options |
---|
Creates a new URL Field
options | Object | See the Field constructor for available options |
---|
Creates a new email Field
options | Object | See the Field constructor for available options |
---|
Creates a new creator Field
options | Object | See the Field constructor for available options |
---|
Creates a new timestamp Field
options | Object | See the Field constructor for available options |
---|
Creates a new choice Field
Required option: values - an array of possible choices, each an array with the first item as the value and the second as its label.
options | Object | See the Field constructor for available options |
---|
Creates a new numberChoice Field
Required option: values - an array of possible choices, each an array with the first item as the value and the second as its label.
options | Object | See the Field constructor for available options |
---|
Creates a new Embedded Field
Required option: type - the Type definition to embed
options | Object | See the Field constructor for available options |
---|
Creates a new EmbeddedList Field
Required option: type - the Type definition to embed
options | Object | See the Field constructor for available options |
---|
Flash messages help you store state between requests, such as reporting a successful or failed operation after a redirect.
The flash message implementation in this module handles both fallback couchdb mode, using cookies to persist state between requests, as well as supporting client-side operation, correctly handling new messages even inside the callbacks of async functions.
Flash messages only persist for the next request or the next template render! That means 2 redirects without explicitly currying the flash messages will cause the messages to be lost.
Reads the flash messages cookie from a request object, returning an array of incoming messages.
req | Object |
---|
Reads the flash messages cookie from the browser, returning an array of incoming messages.
Adds a flash_messages property to a request containing all incoming messages.
req | Object |
---|
Get's all current flash messages, stopping them from being outgoing on the next request so they're not repeated.
req | Object |
---|
Filters all available messages on a request object, returning only those flagged as outgoing (sending in the response to be made available to the next request).
req | Object |
---|
Updates a response object after a list, show or update function has returned, setting the flash messages cookie to include the outgoing messages.
req | Object |
---|---|
res | Object |
Creates a new flash message object, associating it with the given request.
req | Object |
---|---|
msg | String |
Stores a list of messages in the flash messages cookie. This function is for client-side use.
req | Object |
---|---|
messages | Array |
Adds a new flash message for the current request. If the list, show or update function has not returned, it's added to the response Set-Cookie header, otherwise (if its the result of a client-side async operation) it's added directly to the browsers cookies.
req | Object |
---|---|
msg | String |
Used on both Fields and Types to check a given user is authorized to make a change to a document.
Field's new value should match current user's name
Checks if the user has a specific role
role | String |
---|
The value of this field should never change after the document has been created.
User's name should match the *old* value of the given field. A field can be specified using a string or an array of strings (like a path), eg:
usernameMatchesField('creator') usernameMatchesField(['meta','creator']) { creator: 'name', meta: {creator: 'name2'} }
path |
---|
Checks that user's context has a username
Runs an array of permissions functions and checks that all of them pass, returning all failures.
perms | Array |
---|
Tests to see if any one permission function passes, returning on the first success. If all permissions fail, then all errors are returned.
perms | Array |
---|
Treat new and old values like new documents of a given type, and attempt to authorize the value against the type's permissions. Useful when handling permissions for an embedded type.
Can be combined with permissions.any or permissions.all to extend the permissions for an embedded type field. For example, the following might allow both the owner of the parent document and the owner of the comment itself to remove it.
comment: fields.embed({
type: types.comment,
permissions: {
remove: permissions.any([
permissions.usernameMatchesField('creator'),
permissions.inherit(types.comment)
])
}
});
type | Type Object |
---|
Functions related to the management of user sessions and account information.
Creates a fake request to /_session to pass to sessionChange, useful when using functions such as templates.render
userCtx | Object |
---|---|
callback | Function |
Calls sessionChange if exported from the currently loaded app.
userCtx | Object |
---|---|
callback | Function |
Logs out the current user.
callback | Function |
---|
Attempt to login using the username and password provided.
username | String |
---|---|
password | String |
callback | Function |
Returns the current user's session information.
callback | Function |
---|
Returns the authentication database for the current user's session.
callback | Function |
---|
Creates a new user document with given username and password.
username | String |
---|---|
password | String |
callback | Function |
Kanso uses Dust templates for rendering pages. To learn more about the syntax, see the Dust site.
Since Dust stores compiled templates on the module itself, the templates module does some interesting things to work around the lack of a module cache in CouchDB. Because of this, compiled templates are automatically added to this module from your templates folder each time your app is pushed to CouchDB. You can see a list of the loaded template names on the 'loaded' property of this module.
Synchronously render dust template and return result, automatically adding baseURL to the template's context. The request object is required so we can determine the value of baseURL.
name | String |
---|---|
req | Request Object |
context | Object |
Document types can be used to ease the validation of updates and check permissions when creating, editing or deleting documents.
Creates a new Type object
options | Object | see below for available properties |
---|
fields | Object | Field objects to use as the Type's schema |
---|---|---|
permissions | Object | a permissions check function or an object containing separate functions to run on add, remove and update operations |
Run field validators against document and check for missing required fields or extra fields when the Types's allow_extra_fields property is set to false.
doc | Object |
---|---|
rawDoc | Object |
Run field permissions checks against userCtx and document.
nDoc | Object | new document |
---|---|---|
oDoc | Object | old document |
userCtx | Object | user context object |
Authorize a specific field, returning all permissions errors as an array with each error's field property prefixed by the current path.
f | Field | field object |
---|---|---|
nDoc | Object | new document |
oDoc | Object | old document |
nVal | new field value | |
oVal | old field value | |
user | Object | user context object |
path | Array | current path |
Authorizes an object containing fields or other sub-objects, iterating over each property and recursing through sub-objects to find all Fields.
Returns an array of permissions errors, each with a field property set to the path of the field which caused the error.
f | Field | field object |
---|---|---|
nDoc | Object | new document |
oDoc | Object | old document |
nVal | new field value | |
oVal | old field value | |
user | Object | user context object |
path | Array | current path |
Create's a new object for this Type. Pre-filling any default values and providing a new _id value. This is a convenient funciton to use when creating a type to embed within another.
userCtx | Object |
---|---|
callback | Function |
Calls validation and permissions functions relevant to a document update. This should be called from your app's exported validate_doc_update function if you wish to use kanso Types in you project.
Throws on error.
types | Object |
---|---|
newDoc | Object |
oldDoc | Object |
userCtx | Object |
General utility functions used by Kanso. Some functions were moved here from other modules (such as core), to avoid a circular dependency bug in CouchDB.
The utils module exports some useful properties you may want to use inside your own functions:
isBrowser | Boolean | whether or not the current code is running in the browser (not in CouchDB) |
---|---|---|
initial_hit | Boolean | set to true when the page is first loaded from CouchDB |
userCtx | Object | stores cached user context information (username etc) |
session | Object | stores cached extended user session info |
Returns the path to prefix to any URLs. When running behind a virtual host, there is nothing to prefix URLs with. When accessing the app directly, URLs need to be prefixed with /db/_design/appname/_rewrite.
The request object argument is only required when run server-side.
req | Object |
---|
Traverses an object and its sub-objects using an array of property names. Returns the value of the matched path, or undefined if the property does not exist.
getPropertyPath({a: {b: 'foo'}}, ['a','b']) -> 'foo'
obj | Object |
---|---|
path | Array |
Traverses an object and its sub-objects using an array of property names. Sets the value of the matched property.
setPropertyPath({}, ['a','b'], 'foo') -> {a: {b: 'foo'}}
obj | Object |
---|---|
path | Array |
val |
Returns the name of the constructor function for an object. This is used as a workaround for CouchDB's lack of a module cache, where instanceof checks can break if a module is re-eval'd.
obj | Object |
---|
Call function with arguments, catch any errors and add to an array, returning the modified array.
arr | Array |
---|---|
fn | Function |
args | Array |
Validation functions used to validate Field contents.
Tests that the field's value is greater than 'min'.
min | Number |
---|
Tests that the field's value is less than 'max'
max | Number |
---|
Tests that the field's value is greater than 'min' AND less than 'max'
min | Number |
---|---|
max | Number |
Tests that the field's value length is greater than 'val'
val | Number |
---|
Tests that the field's value length is less than 'val'
val | Number |
---|
Tests that the field's value length is greater than 'min' AND less than 'max'
min | Number |
---|---|
max | Number |
Tests field's value against a regular expression
re | RegExp | can be a string or a RegExp object |
---|---|---|
message | String | (Optional) a custom error message to throw |
Tests that field's value is a valid email address using a regular expression.
Tests that field's value is a valid URL using a regular expression.
Detects embedded documents with missing _id properties and returns an array of Error objects for each occurence. Returns an empty array if all documents have a populated _id property.
Used by the EmbeddedList field type.
Widgets define the way a Field object is displayed when rendered as part of a Form. Changing a Field's widget will be reflected in the admin app.
Widget constructor, creates a new Widget object.
type | String |
---|---|
options | Object |
classes | Array | classes to add to the HTML element |
---|---|---|
id | String | id to use for the HTML element |
Converts a widget to HTML using the provided name and parsed and raw values
name | String |
---|---|
value | |
raw |
Creates a new text input widget.
options | Object |
---|
Creates a new password input widget.
options | Object |
---|
Creates a new hidden input widget.
options | Object |
---|
Creates a new textarea input widget.
options | Object |
---|
Creates a new checkboxinput widget.
options | Object |
---|
Creates a new select input widget.
options | Object |
---|
Typing 'kanso' with no arguments will present you with a list of available commands. More information can be found by typing 'kanso help' optionally followed by the name of the command you need help with.
Upload a project to a CouchDB instance.
kanso push [OPTIONS] DB [PATH] Parameters: DB The CouchDB instance to upload the app to PATH The project path to load the app from Options: --minify Compress CommonJS modules using UglifyJS --minify-attachments Compress .js attachments --baseURL PATH Force the baseURL to a specific value. (allows vhosts on CouchDB < v1.1.x)
Push a file or directory of JSON files to DB.
kanso pushdata [OPTIONS] DB PATH Parameters: DB The CouchDB instance to upload the documents to PATH A file or directory containing JSON documents to upload Options: -f, --force Ignore document conflict errors and upload anyway
Upload the kanso admin app to a CouchDB instance.
kanso pushadmin [OPTIONS] DB Parameters: DB The CouchDB instance to upload the app to Options: --minify Compress CommonJS modules using UglifyJS --minify-attachments Compress .js attachments --baseURL PATH Force the baseURL to a specific value. (allows vhosts on CouchDB < v1.1.x)
Create a new project skeleton.
kanso create PATH Parameters: PATH Path to create a new project skeleton at, project name defaults to last directory in this path
Show help specific to a command.
kanso help [COMMAND] Parameters: COMMAND The kanso command to show help on
Load a project and output resulting JSON
kanso show [PATH] Parameters: PATH Path to project directory to show (defaults to ".")
Returns UUIDs generated by a CouchDB instance.
kanso uuids [OPTIONS] [URL] Parameters: URL The CouchDB instance to generate UUIDs from (defaults to http://localhost:5984) Options: -n [NUM], --number [NUM] The number of UUIDs to generate (default: 1)