# Deployd

Deployd lets you quickly build secure, dynamic JavaScript and Mobile apps without writing backend code. Instead you boot a simple server that is very good at securely proxying requests to a storage layer such as a database. This enables your un-trusted client code to do things it never could before, such as write directly to a database without a custom application running in-between.

Instead of reinventing a protocol, deployd embraces HTTP. This means that any HTTP client, such as a JavaScript app, a mobile app, or even another server, can securely interact with your data without having to setup a web server and write a custom backend.

## Quick start

Currently deployd requires mongodb to be installed. You can download mongodb here. It also requires `node.js` >= v0.6.0. You can download node here.

Install deployd from npm. `sudo` may be required depending on your setup.

    $ [sudo] npm install deployd -g

Create an `index.html` file in a new directory.

    <!doctype html>
    <html>
      <head>
        <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
        <script src="/dpd.js"></script>
        <script> console.log(dpd); </script>
      </head>
      <body>
      </body>
    </html>

Run the following command from the same directory where you created index.html. See `dpd -h` for more info on how to use the command line interface.

    $ dpd -d

This will open up the dashboard where you can manage your deployd server. You can create resources and manage their data.

Open up `http://localhost:2403` your browser console. You should see the `dpd` object logged out. This is an api to all of your resources.

If you created a `/todos` collection you could add a new todo with:

    dpd.todos.save({title: 'Foo the bar', completed: true}, function(todo) {
      console.log(todo);
    });

If you created a `/users` user collection you could log in a user with:

    dpd.users.login({email: 'foo@bar.com', password: 'mypassword'}, function(user) {
      console.log(user);
    });

## How does it work?

### Storage

Deployd greatly simplifies web and mobile app development by acting as a proxy between untrusted clients (browser, phones, etc) and your database, allowing you to do more on the client than ever before. This added benefit also comes with added responsibility to secure the newly opened APIs directly to your data. Deployd solves this by validating every request against rules you define in the dashboard or in familiar JavaScript.

Once a request is validated for input, authorization, and passes any custom validation, it is proxied to the storage layer (database abstraction). This means you do not have to write backend code to expose data to your clients. Data is instantly available.

### REST

Deployd uses REST to expose database commands to clients.

REST is a web service design pattern that conforms closely to HTTP itself. In Deployd, HTTP methods or verbs have meaning:

- GET - Load a resource without modifying it (this is a browser's default method)
- POST - Create a resource, or send data to a special that doesn't fit within these methods
- PUT - Update an existing resource
- DELETE - Destroy an existing resource

In Deployd, HTTP response codes are also important:

- 200 OK - The request succeeded
- 204 No Content - The request succeeded, but there is no content to return (for example, after a deletion, or requesting an empty list)
- 400 Bad Request - The request did not pass validation. Change the parameters and try again.
- 401 Unauthorized - The request's session does not have permission to access that resource.
- 404 Not Found - That URL does not reference an existing resource
- 500 Internal Server Error - Deployd has failed to process the request due to an unexpected error.

Deployd exposes everything, even low level functionality, securely over http (with the appropriate auth keys). This lets you use deployd however you want as long as your client can speak http.

### Resources

Deployd servers are built using resources. Each resource handles its own unique URL. For example a list of todos could be served as a collection resource.

    GET /todos?q={"$orderby": "created"}

Deployd will route this to the `/todos` collection resource and hand it off to its module. The collection resource will execute a fetch from the storage engine passing the query `{"$orderby": "created"}` and execute the `GET` event handler if one has been attached, passing the event handler the current session and data retrieved. Finally, the http response will be handed the final object, potentially modified by an event handler.

# JavaScript Client API

Its very easy to access the deployd api from browser JavaScript. Just include `<script src="/dpd.js"></script>`. Deployd automatically builds and generates your data api for you.

## Collections

Each collection gets several methods to create/update, read/query, and delete data. The following examples assume you have created a `/todos` collection.

### save(data, callback)

Save the provided data object to the collection:

    dpd.todos.save({creator: 'ritch', title: 'foo the bar', order: 7, done: false}, function(todo, err) {
      if(err) return console.log(err);
      console.log(todo); // {title: 'foo the bar', order: 7, done: false, _id: "4b5783300334000000000aa9"}
    });

If the object already has an `_id` the existing object in the collection with the matching id will be updated.

    dpd.todos.save({_id: "4b5783300334000000000aa9", done: true}, function(todo, err) {
      if(err) return console.log(err);
      console.log(todo); // {title: 'foo the bar', order: 7, done: true, _id: "4b5783300334000000000aa9"}
    });

### post(data, callback)

Creates the provided object in the collection:

    dpd.todos.post({creator: 'ritch', title: 'foo the bar', order: 7, done: false}, function(todo, err) {
      if(err) return console.log(err);
      console.log(todo); // {title: 'foo the bar', order: 7, done: false, _id: "4b5783300334000000000aa9"}
    });

### get([query], callback)

Query the collection using the optional mongo query object.

Get all the todos with a creator `'ritch'`:

    dpd.todos.get({creator: 'ritch'}, function(todos, err) {
      if(err) return console.log(err);
      console.log(todos); // [{title: 'foo the bar', order: 7, done: true}, ...]
    });

### first([query | id], callback) or getOne([query | id], callback)

Get the first object from the collection using the optional mongo query object or an id.

Get a todo by id:

    dpd.todos.first("4b5783300334000000000aa9", function(todo, err) {
      if(err) return console.log(err);
      console.log(todo); // {title: 'foo the bar', order: 7, done: true, _id: "4b5783300334000000000aa9"}
    });

Get a todo with specified properties:

    dpd.todos.first({creator: 'ritch', title: 'foo the bar'}, function(todo, err) {
      if(err) return console.log(err);
      console.log(todo); // {title: 'foo the bar', creator: 'ritch', order: 7, done: true, _id: "4b5783300334000000000aa9"}
    });

### put([id], data, callback)

Updates the object with the specified id with the provided properties. If no id is provided, it will be inferred from the data's `_id` property.

Update a todo:

    dpd.todos.put("4b5783300334000000000aa9", {order: 3}, function(todo, err)) {
      if(err) return console.log(err);
      console.log(todo); // {title: 'foo the bar', creator: 'ritch', order: 3, done: true, _id: "4b5783300334000000000aa9"}
    });

### del(id, callback)

Delete the object from the collection with the specified id.

Delete a todo by id:

    dpd.todos.del("4b5783300334000000000aa9", function(success, err) {
      if(err) return console.log(err);
      console.log(success); // true
    });

## Users Collection

Users collections include methods to login and logout users as well as return the current user. Each users collection gets the same methods to create/update, read/query, and delete data as a regular collection. The following examples assume you have created a `/users` collection.

### users.post(user, callback)

Register a new user. Passwords will automatically be removed from responses.

    dpd.users.post({email: 'foo@bar.com', password: 'mypassword'}, function(user, err) {
      if(err) return console.log(err);
      console.log(user); // {email: 'foo@bar.com', _id: "4b5783300334000000000aa9"}
    });

### users.login(credentials, callback)

Login a user with the given credentials.

    dpd.users.first({email: 'foo@bar.com', password: 'mypassword'}, function(user, err) {
      if(err) return console.log(err);
      console.log(user); // {email: 'foo@bar.com', _id: "4b5783300334000000000aa9"}
    });

### users.me(callback)

Get the currently logged in user.

    dpd.users.me(function(user, err) {
      if(err) return console.log(err);
      console.log(user); // {email: 'foo@bar.com', _id: "4b5783300334000000000aa9"}
    });

### users.logout(callback)

Logout the current user.

    dpd.users.logout(function(success, err) {
      if(err) return console.log(err);
      console.log(success); // true
    });

# Collection Resource

A Collection resource allows client apps to save and query data.

## Setting up a collection

After creating a Collection resource in the dashboard, you can set up the schema that will automatically validate data sent to the resource url over HTTP. You can configure this schema in the dashboard.

The Data view in the dashboard allows you to edit the Collection manually.

## Property types

You can currently use the following property types:

- String - Arbritrary text data
- Number - Numeric value, supports floating points
- Boolean - True or false
- Date - A specific point in time

## Formats

When POSTing or PUTing data to a resource `/path`, you must format the request body as a JSON string and pass the header "Content-Type: application/json".

## Saving data

To save data, send a POST request to the root of the Collection:

    POST /people
    Content-Type: application/json
    {
      "age": 23,
      "firstName": "Joe",
      "lastName": "Smith"
    }

The server will respond with the object, which will have a new `_id` property.

    200 OK
    {
      "_id": "4f71fc7c2ba744786f000001",
      "age": 23,
      "firstName": "Joe",
      "lastName": "Smith"
    }

This `_id` is used to find the object's URL (i.e. `/people/4f71fc7c2ba744786f000001`)

## Listing data

A GET request to the root of the Collection will return an array of objects in the collection:

    GET /people

    200 OK
    [
      {
        "_id": "4f71fc7c2ba744786f000001",
        "age": 23,
        "firstName": "Joe",
        "lastName": "Smith"
      },
      {
        "_id": "4f71fe8b2ba744786f000002",
        "age": 36,
        "firstName": "John",
        "lastName": "Doe"
      }
    ]

## Retrieving a specific object

A GET request at an object's URL will return the properties of that object:

    GET /people/4f71fc7c2ba744786f000001

    200 OK
    {
      "_id": "4f71fc7c2ba744786f000001",
      "age": 23,
      "firstName": "Joe",
      "lastName": "Smith"
    }

## Updating an object

A PUT (or POST) request at an object's URL will update the properties specified on the object.

    PUT /people/4f71fc7c2ba744786f000001
    Content-Type: application/json
    {
      "age": 24
    }

The server will respond with the entire object:

    200 OK
    {
      "_id": "4f71fc7c2ba744786f000001",
      "age": 24,
      "firstName": "Fred",
      "lastName": "Smith"
    }

## Deleting an object

A DELETE request at an object's URL will permanently remove that object from the collection:

    DELETE /people/4f71fc7c2ba744786f000001

    204 No Content

## Filtering results

You can add querystring parameters to a GET request at the root to filter the results by properties specified:

    GET /people?firstName=Joe&lastName=Smith

NOTE: This currently only works for String properties.

## Advanced querying

If you need to query additional types of properties, pass a JSON object as the `q` parameter with the properties you wish to filter:

    GET /people?q={
      "age": 23
    }

The `q` parameter supports MongoDB's query language for particularly advanced queries. Note that Collections do not currently support embedded documents or arrays.

    GET /people?q={
      "$orderby": { "age": 1 },
      "name": {
        "$regex": "^j"
        "$options": "i",
      }
    }

# Collection Event Handlers

You can attach micro-scripts to events to add logic and validation to your objects. Collections currently support the following events:

- On GET - called when data is read
- On Validate - called before creating or updating an object.
- On POST - called when data is created
- On PUT - called when data is updated
- On DELETE - called when data is destroyed

## Reading and setting properties

In an event micro-script, the `this` object refers to the current object, and has all of the properties of the object.

You can set values on the `this` object during an On Post or On Put event. These changes will be saved to the database.

    // On POST:
    this.dateCreated = new Date();

    // On Validate:
    this.totalScore = this.level1Points + this.level2Points;

Note: If you intend for a property to be "automatic" (calculated by the server, and never provided by the client), you will need to mark it as Optional in the dashboard.

## Accessing the current user

If the request is coming from a logged in User, you can use the "me" object to access their properties.

    // On POST:
    this.creator = me._id;

## Cancelling an event

You can stop any event by calling the `cancel(message, [code])` method.

    //On DELETE:
    if (this.protected) {
      cancel('This post is protected and cannot be deleted');
    }

    DELETE /posts/123456

    400 Bad Request
    {
      "message": "This post is protected and cannot be deleted"
    }

You can pass an integer to the `cancel()` method as the second parameter to set the HTTP status code. For example, 401 means "Unauthorized".

    //On PUT
    if (this.creator !== me._id) {
      cancel("You cannot edit this post because it is not yours!", 401);
    }

    PUT /posts/13456
    Content-Type: application/json
    { ... }

    401 Unauthorized
    {
      "message": "You cannot edit this post because it is not yours!"
    }

## Validation

Use the `error(name, message)` function to add a validation error.

    //On Validate
    if (this.age < 18) {
      error('age', 'must be older than 18')
    }

    POST /people
    {
      "firstName": "Joe",
      "lastName": "Smith",
      "age": 12
    }

    400 Bad Request
    {
      errors: {
        "age": "must be older than 18"
      }
    }

## Hiding properties

If you wish to hide certain properties from a user, use the `hide(propertyName)` function.

    //On Get
    if (this.creator !== me._id) {
      hide('lastName');
      hide('age');
    }

## Protecting properties from modification

Use the `protect(propertyName)` function to protect specified properties during a PUT.

    //On Put
    protect('createdDate');

# User Collection Resource

A User Collection resource behaves much like the standard Collection resource, but adds the ability to authenticate with a username and password.

## Special properties

The User Collection contains two special properties:

- email - For security, hidden by default on all users except the current user.
- password - Never readable under any circumstances. Can only be set when the user is logged in, when creating a new user, or from the Dashboard.

## Registering a user

First create a user by POSTing it to the root of the collection. For this example our collection will be called `/users`.

    POST /users
    Content-Type: application/json
    {
      "email": "foo@bar.com",
      "password": "barfoo"
    }

## Authenticating a user

To login a user, send a POST request to `/<collection name>/login`:

    POST /users/login
    Content-Type: application/json
    {
      "email": "foo@bar.com",
      "password": "barfoo"
    }

The server will respond with the user, without the password.

    200 OK
    {
      "_id": "4f71fc7c2ba744786f000001",
      "email": "foo@bar.com"
    }

## Current user

The currently logged in user is available by sending a GET request to `/users/me`.

    200 OK
    {
      "_id": "4f71fc7c2ba744786f000001",
      "email": "foo@bar.com"
    }

## Logging out

To logout a user send a POST request to `/<collection name>/logout`:

    204 No Content