Samples


Intro

Below we have several quick-start apps and code samples to help you get up and running in no time. These projects demonstrate the various capabilities and design of the Backbench platform. It is not intended as a finished product or solution but rather as an example of how to use our features in solving functional problems for your project, application or team. If you are new to Backbench, we recommend beginning by working through our Getting Started section.

There are many possible Use Cases and features that could be included in the samples section as we go forward. Our intention is to provide real-world examples and a kitchen-sink of features so that you can jumpstart your own implementations. We’re always interested in feedback as to what we should add next! Please let us know your thoughts regarding what is important to you.

Node.js Samples

In this section we will learn to make quick-start apps using Node.js on BackBench.

Address Book App

In this example you will be able to add, save and search addresses using backbench via Facebook, Google and Github oauth.

What You'll Need:

  • Backbench account - Sign Up, the personal account will always remain free to use.
  • GitHub account - Create an account and create an app on github developers from

Backend

Prerequisites for sample app:

  1. Sign In to Backbench account.
  2. Select +, in the upper right corner to create a Bench using Node.js. For example, say "addressbookapp" and select CREATE or hit Enter.

Navigate through each tabs and follow the guidelines as instructed.

...
  1. Select +, in the upper right corner to create a Module. For example, say "db.js" and select CREATE or hit Enter.
  2. Copy and paste the code module from below.
  3. Replace ACCESS_KEY in the accessKey:"ACCESS_KEY" section, found in your bench details.
  4. Select Save.

db.js

    var request = require("request");
    var accessKey = ACCESS_KEY;
    var benchId = "addressbook";
    var userId = "mybench";
    
    module.exports={
        "set": function(key, value, callback){
            request.post({ 
                 url:"https://memory.backbench.io/",
                 body: {
                    "cmd": "bb:mem:set",
                    "auth": {
                         "benchId": benchId,
                         "userId": userId,
                         "accessKey": accessKey 
                    },
                    "args": {
                        "key": key,
                        "value": value
                    }
                 },
                 json: true
             }, function (error, response, body) {
                    if (error) {
                        callback(error);
                    } else{
                        callback(undefined, body);
                    }
             });
        }, 
        "get": function(key, cb){
           request.post({
                url: "https://memory.backbench.io/",
                body: {
                    "cmd": "bb:mem:get",
                    "auth": {
                        "benchId": benchId,
                        "userId": userId,
                        "accessKey": accessKey
                      },
                    "args": {
                        "key": key
                    }
                },
                json: true
            }, function (error, response, body) {
                if (error) {
                    cb(error);
                } else{
                    cb(undefined, body.reply);
                }
            }); 
        },
        "delete": function(key, cb){
           request.post({
                url: "https://memory.backbench.io/",
                body: {
                    "cmd": "bb:mem:del",
                    "auth": {
                        "benchId": benchId,
                        "userId": userId,
                        "accessKey": accessKey
                    },
                    "args": {
                        "key": key
                    }
                },
                json: true
            }, function (error, response, body) {
                if (error) {
                    cb(error);
                } else{
                    cb(undefined, body.reply);
                }
            }); 
        }
    };   
  1. Select +, in the upper right corner to create a Module. For example, say "auth.js" and select CREATE or hit Enter.
  2. Copy and paste the code module from below.
  3. Select Save.

auth.js

    const utils = require("./utils")

    exports.endpoint = function(req, cb){
        let code = req.body.code || ""
        if (!code) cb({"error": "Invalid user"})
        utils.authId_retrieve(code, (authId)=>{
            console.log(authId);
            if (!authId) return cb({"error": "Invalid user"}) 
            
            utils.userId_retrieve(authId, (userId)=>{
                if (!userId) cb({"error": "Invalid user"})
                
                utils.set_authId_to_userId(authId, userId, function(){
                     cb(null, {"authId": authId, "userId": userId})
                });
            })
        })
    }    
  1. Select +, in the upper right corner to create a Module. For example, say "index.js" and select CREATE or hit Enter.
  2. Copy and paste the code module from below.
  3. Select Save.

index.js

        const utils = require("./utils")

        //api - view layer
        exports.endpoint = function(req, cb){
            let authid = req.body.authid || "";
            if (!authid) return cb({"error": "Invalid user"})
            utils.get_authId_to_userId(authid, function(uid){
                console.log(authid)
                console.log(uid)
                
                if (!uid) cb({"error": "Invalid user"})
                utils.get_address(uid, function(data){ //api level response
                    if(!data) cb(undefined, [])			
                    else cb(null, data)
                })
            })
        }     
  1. Select +, in the upper right corner to create a Module. For example, say "init.js" and select CREATE or hit Enter.
  2. Copy and paste the code module from below.
  3. Select Save.

init.js

                const db = require("./db");

                exports.endpoint = (req, cb)=>{
                    db.set("authids", {}, function(){
                        db.set("addresses", {}, function(){
                            cb({"status": "success"})
                        })
                    })   
                }
            
  1. Select +, in the upper right corner to create a Module. For example, say "new.js" and select CREATE or hit Enter.
  2. Copy and paste the code module from below.
  3. Select Save.

new.js

                const utils = require("./utils")

                exports.endpoint = function(req, cb){
                    let authid = req.body.authid || "";
                    if (!authid) 
                        cb({"error": "Invalid user"})
                
                    let name = req.body.name || '';
                    if (!name || name === ' ') 
                        cb({"error": "Name empty"})
                        
                    let address = req.body.address || '';
                    if (!address || address === ' ') 
                        cb({"error": "Address empty"})
                        
                    let mobile = req.body.mobile || '';
                    let email = req.body.email || '';
                
                    
                    utils.get_authId_to_userId(authid, function(uid){
                        if (!uid) cb({"error": "Invalid user"})
                        
                        var pb = {address: address, name: name, mobile: mobile, email: email};
                        utils.set_address(uid, pb, function(resp){
                            if (!resp){
                                cb({"error": "internal error"})
                            }
                            cb(undefined, {data: resp})
                        })
                        
                    })
                } 
            
  1. Select +, in the upper right corner to create a Module. For example, say "package.json" and select CREATE or hit Enter.
  2. Copy and paste the code module from below.
  3. Select Save.

package.json

                {
                    "dependencies": {
                        "request": "^2.83.0"
                    }
                }
            
  1. Select +, in the upper right corner to create a Module. For example, say "utils.js" and select CREATE or hit Enter.
  2. Copy and paste the code module from below.
  3. Replace client_id and client_secret in the client_id: "client_id", client_secret: "client_secret", section, found on Github developers console.
  4. Select Save.

utils.js

    const request = require("request");
    const db = require("./db");
    
    module.exports = {
    "get_authId_to_userId": function(authid, callback){ //outputs id or null
            db.get("authids", function(err, auths){
                if (!auths){
                    auths = {}
                }
                
                if(auths[authid]){
                    callback(auths[authid])
                } else{
                    callback("")
                }
            })
        },
        "set_authId_to_userId": function(authid, id, callback){ //outputs id or null
            db.get("authids", function(err, authids){
                
                if (!authids){
                    authids = {}
                }
                authids[authid] = id;
                db.set("authids", authids, function(){
                    callback({"status": "done"})
                })
            })
        },
        "authId_retrieve": function(code, callback){
            request({
                method: "POST",
                url:'https://github.com/login/oauth/access_token', 
                json: {
                    'client_id': process.env.CID,
                    'client_secret': process.env.CSEC,
                    'code': code
                },
                headers: {
                    "Accept": "application/json"
                }
            }, function(err,httpResponse,body){
                if (err){
                    console.log(err)
                    callback("")
                }
                console.log(body)
                callback(body.access_token)
            })
            //callback("auth_id")
        },
        "userId_retrieve": function(at, callback){
            request({
                url: "https://api.github.com/user?access_token="+at,
                method: "GET",
                headers: {
                    "User-agent": "api"
                }
            }, function(err,httpResponse,body){
                if (err){
                    console.log(err)
                    callback("")
                }
                callback(JSON.parse(body).login)
            })
            //callback("user_id")
        },
        "get_address": function(uid, callback){
            db.get("addresses", (err, addresses)=>{
                if (!addresses) addresses = {}
                    
                if(addresses[uid]){
                    callback(addresses[uid])
                } else{
                    callback("")
                }
            })
        },
        "set_address": function(uid, data, callback){
            db.get("addresses", function(err, addresses){
                if (!addresses){
                    addresses = {}
                }
                if(!addresses[uid]){
                    addresses[uid] = []
                }
                addresses[uid].push(data)
                db.set("addresses", addresses, function(err, res){
                    console.log(err, res)
                    callback(addresses)
                })
                
            })
        }
    } //all one level arguments                                          
  1. Select +, in the upper right corner to create a Module. For example, say "search.js" and select CREATE or hit Enter.
  2. Copy and paste the code module from below.
  3. Select Save.

search.js

    const utils = require("./utils");

    exports.endpoint = function(req, cb){
        let authid = req.body.authid;
        let keyword = req.body.keyword;
        
        if (!authid) {
            return cb({"error": "Invalid user"})
        }
        if (!keyword) {
            return cb({"error": "Invalid user"})
        }
        
        utils.get_authId_to_userId(authid, function(uid){
            if(!uid){
                return cb({"error": "Invalid user"})
            }
            utils.get_address(uid, function(addresses){ //api level response
                if(!addresses) {
                    addresses = []
                }			
                const result = addresses.filter( address => address.name.includes(keyword));
                if (!result){
                    return cb({"error": "no results found"})
                } else{
                    return cb(undefined, {data: result})
                }
            })
        })
    }
                                            
...
...
  1. Select +, in the upper right corner to create a file . For example, say "login.html" and select CREATE or hit Enter.
  2. Copy and paste the codefrom below.
  3. Replace client_id and client_secret in the client_id: "client_id" section, foound Facebook, Google and Github developers console.
  4. Select Save.

login.html

    
        <!DOCTYPE html>
        <html>
        <head>
            <title>Address Book App</title>
            <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
            <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
            <link rel="stylesheet" href="./style.css">
        </head>
        <body>
        <nav class="navbar navbar-default navbar-fixed-top">
            <div class="container">
                <a class="navbar-brand" href="#page-top">Address Book App</a>
            </div>
        </nav>
        <div class="btn-contain">
            <a class="loginBtn loginBtn--github btn-log" href="https://github.com/login/oauth/authorize?client_id=de7dd5436f5bed9ed183">Login with Github</a>
            <p class="love">Made with ♥️ in India. Hosted on <span><a href="https://backbench.io/" target="_blank">backbench.io</a></span></p>
        </div>
        </body>
        </html>            
    
  1. Select +, in the upper right corner to create a file . For example, say "index.html" and select CREATE or hit Enter.
  2. Copy and paste the codefrom below.
  3. Select Save.

index..html

        
            <!DOCTYPE html>
            <html>
            <head>
                <title>Address Book App</title>
                <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
                <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
                <link rel="stylesheet" href="./style.css">
            </head>
            <body>
            <nav class="navbar navbar-default">
                <div class="container">
                    <!-- Brand and toggle get grouped for better mobile display -->
                    <div class="navbar-header ">
                        <a class="navbar-brand" href="">Address Book App</a>
                    </div>
                    <div class="collapse navbar-collapse"> 
                        <a class="navbar-link btn btn-default navbar-btn navbar-right" href="#" onclick="localStorage.clear();location.href = '/login.html';">Log out</a>
                        <p class="navbar-text navbar-right">Signed in as <span id="userId"></span></p>
                    </div>
                </div>
            </nav>
            <div class="container">
            <div class="form-inline">
            <form class="form-group" id="searchAddress">
                <input type="text" class="form-control" id="searchText" placeholder="Enter name to search..." min="3">
                <button class="btn btn-default">Submit</button>
            </form>
            <div class="pull-right">
            <button style="margin-bottom:10px" id="collapse" class="btn btn-primary" type="button" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
              Add New Address
            </button>
            </div>
            </div><br style="clear: both">
            <div class="collapse" id="collapseExample">
            <hr>
            <form id="addressForm">
            <div class="form-group">
                <label for="exampleInputName">Name</label>
                <input type="text" class="form-control" id="name" placeholder="Enter Name" required="">
            </div>
            <div class="form-group">
                <label for="exampleInputEmail">Email</label>
                <input type="email" class="form-control" id="email" placeholder="Enter Email">
            </div>
            <div class="form-group">
                <label for="exampleInputMobile">Mobile No.</label>
                <input type="number" class="form-control" id="mobile" placeholder="Enter mobile no." min="1111111111" max="999999999999">
            </div>
            <div class="form-group">
                <label for="exampleInputAddress">Address</label>
                <textarea class="form-control" rows="4" id="address" placeholder="Enter Address"></textarea>
            </div>
            <button id="addAddress" class="btn btn-default">Submit</button>
            </div>
            </form>
            
            <table class="container table table-hover" id="addressTable">
                <thead>
                  <tr>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Mobile</th>
                    <th>Address</th>
                  </tr>
                </thead>
                <tbody>
                    <tr></tr>
                </tbody>
            </table>
            
            <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
            <script src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
            <script type="text/javascript">
                var userId = localStorage.getItem("userId") || "";
                var authId = localStorage.getItem("authId") || "";


                if (userId) {
                    $("#userId").html(userId);
                } else {
                    location.href = "/login.html"
                }

                $(document).ready(function () {

                    $.post("/index", { authid: authId }, function (data) {
                        data.forEach(function (d) {
                            $('#addressTable tr:last').after('<tr><td>' + d.name + '</td><td>' + d.email + '</td><td>' + d.mobile + '</td><td>' + d.address + '</td></tr>');
                        })
                    })
                })


                $("#addressForm").submit(function (e) {
                    e.preventDefault();

                    var name = $("#name").val();
                    var email = $("#email").val();
                    var mobile = $("#mobile").val();
                    var address = $("#address").val();


                    $("#addresses").append("<li>" + name + "</li>");
                    $.post("/new", { authid: authId, address: address, name: name, email: email, mobile: mobile }, function (data) {
                        $('#addressTable > tbody:last-child').append('<tr><td>' + name + '</td><td>' + email + '</td><td>' + mobile + '</td><td>' + address + '</td><td></tr>');
                        $("#name").val(""); $("#email").val(""); $("#mobile").val(""); $("#address").val("");
                        if (!data) {
                            alert("Something went wrong")
                            location.reload();
                        }
                    })
                })

                $("#searchAddress").submit(function (e) {
                    e.preventDefault();

                    var keyword = $("#searchText").val();

                    $('#addressTable > tbody').html("<td></td>")
                    $.post("/search", { authid: authId, keyword: keyword }, function (response) {
                        let data = response.data;
                        if (data.length === 0) {
                            $('#addressTable > tbody:last-child').append('<tr><td>No results found</td></tr>');
                        } else {
                            for (var i = 0; i < data.length; i++) {
                                $('#addressTable > tbody:last-child').append('<tr><td>' + data[i].name + '</td><td>' + data[i].email + '</td><td>' + data[i].mobile + '</td><td>' + data[i].address + '</td><td></tr>');
                            }
                        }
                    })
                })
            </script>
            </body>
            </html> 
        
  1. Select +, in the upper right corner to create a file . For example, say "auth.html" and select CREATE or hit Enter.
  2. Copy and paste the codefrom below.
  3. Select Save.

auth.html

        
            <!DOCTYPE html>
            <html>
            <head>
                <title>Address Book App</title>
                <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
                <link rel="stylesheet" href="./style.css">
            </head>
            <body>
            <div class="btn-contain">
            <div class="lds-spinner">
            <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
            </div>
            </div>
            <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
            <script type="text/javascript">
                function getUrlVars() {
                    var vars = [], hash;
                    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
                    for (var i = 0; i < hashes.length; i++) {
                        hash = hashes[i].split('=');
                        vars.push(hash[0]);
                        vars[hash[0]] = hash[1];
                    }
                    return vars;
                }

                var code = getUrlVars()["code"];
                $.post("/auth", { "code": code }, function (data) {
                    console.log(data);
                    localStorage.setItem("userId", data.userId);
                    localStorage.setItem("authId", data.authId);
                    location.href = "/"
                });
            </script>
            </body>
            </html>
        
  1. Select +, in the upper right corner to create a file . For example, say "auth.html" and select CREATE or hit Enter.
  2. Copy and paste the codefrom below.
  3. Select Save.

auth.html

        
            <!DOCTYPE html>
            <html>
            <head>
                <title>Address Book App</title>
                <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
                <link rel="stylesheet" href="./style.css">
            </head>
            <body>
            <div class="btn-contain">
            <div class="lds-spinner">
            <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>
            </div>
            </div>
            <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
            <script type="text/javascript">
                function getUrlVars() {
                    var vars = [], hash;
                    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
                    for (var i = 0; i < hashes.length; i++) {
                        hash = hashes[i].split('=');
                        vars.push(hash[0]);
                        vars[hash[0]] = hash[1];
                    }
                    return vars;
                }

                var code = getUrlVars()["code"];
                $.post("/auth", { "code": code }, function (data) {
                    console.log(data);
                    localStorage.setItem("userId", data.userId);
                    localStorage.setItem("authId", data.authId);
                    location.href = "/"
                });
            </script>
            </body>
            </html>
        
  1. Select +, in the upper right corner to create a file . For example, say "style.css" and select CREATE or hit Enter.
  2. Copy and paste the codefrom below.
  3. Select Save.

style.css

    @import url(https://fonts.googleapis.com/css?family=Maven+Pro:500);
    #userId{
        margin-left: 2px;
        margin-right: 8px;
        font-weight: bold;
    }
    .btn-contain {
        position: fixed;
        top: 50%;
        left: 50%;
        text-align: center;
        /* bring your own prefixes */
        transform: translate(-50%, -50%);
    } 
    a.btn-log {
        color: white;
        text-decoration: none;
        font-weight: bold;
    }
    .love{
        margin-top: 20px;
    }
    .love a{
        color: #111;
        font-family: 'Maven Pro',sans-serif;
        margin: 0;
        text-decoration: none;
    }
    .loginBtn {
        box-sizing: border-box;
        position: relative;
        margin: 0.2em;
        padding: 8px 10px 8px 44px;
        border: none;
        text-align: left;
        line-height: 44px;
        white-space: nowrap;
        border-radius: 0.2em;
        font-size: 16px;
        color: #fff;
        cursor: pointer;
    }
    .loginBtn--github {
        color: #fff;
        background-color: rgba(0,0,0,0.60);
        border-color: rgba(0,0,0,0.2);
    }
    .loginBtn--github:before {
        border-right: #000 1px solid;
        background: url(https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-social-github-20.png) 6px 6px no-repeat;
    }
    .loginBtn:before {
        content: "";
        box-sizing: border-box;
        position: absolute;
        top: 0;
        left: 0;
        width: 34px;
        height: 100%;
    }
    html, body {
        font-family: "Roboto", "Helvetica", sans-serif;
        margin: 0;
        padding: 0;
    }
    .lds-spinner {
      color: black;
      display: inline-block;
      position: relative;
      width: 64px;
      height: 64px;
    }
    .lds-spinner div {
      transform-origin: 32px 32px;
      animation: lds-spinner 1.2s linear infinite;
    }
    .lds-spinner div:after {
      content: " ";
      display: block;
      position: absolute;
      top: 3px;
      left: 29px;
      width: 5px;
      height: 14px;
      border-radius: 20%;
      background: black;
    }
    .lds-spinner div:nth-child(1) {
      transform: rotate(0deg);
      animation-delay: -1.1s;
    }
    .lds-spinner div:nth-child(2) {
      transform: rotate(30deg);
      animation-delay: -1s;
    }
    .lds-spinner div:nth-child(3) {
      transform: rotate(60deg);
      animation-delay: -0.9s;
    }
    .lds-spinner div:nth-child(4) {
      transform: rotate(90deg);
      animation-delay: -0.8s;
    }
    .lds-spinner div:nth-child(5) {
      transform: rotate(120deg);
      animation-delay: -0.7s;
    }
    .lds-spinner div:nth-child(6) {
      transform: rotate(150deg);
      animation-delay: -0.6s;
    }
    .lds-spinner div:nth-child(7) {
      transform: rotate(180deg);
      animation-delay: -0.5s;
    }
    .lds-spinner div:nth-child(8) {
      transform: rotate(210deg);
      animation-delay: -0.4s;
    }
    .lds-spinner div:nth-child(9) {
      transform: rotate(240deg);
      animation-delay: -0.3s;
    }
    .lds-spinner div:nth-child(10) {
      transform: rotate(270deg);
      animation-delay: -0.2s;
    }
    .lds-spinner div:nth-child(11) {
      transform: rotate(300deg);
      animation-delay: -0.1s;
    }
    .lds-spinner div:nth-child(12) {
      transform: rotate(330deg);
      animation-delay: 0s;
    }
    @keyframes lds-spinner {
      0% {
        opacity: 1;
      }
      100% {
        opacity: 0;
      }
    }
    @media (min-width: 320px) and (max-width: 480px) {
      #searchAddress .btn{
          margin-top: 10px;
      }
      .pull-right{
        float: none !important;
      }
    }    
...
  1. Select Endpoints on the left panel and Click +, in the upper right corner to setup the HTTP endpoint.
  2. Give a Path name select CREATE following endpoints.
  3. /auth                 auth
    /index                index
    /new                new
    /init                 init
    /search               search  
    
  4. Enable CORS (Cross Origin Resource Sharing)
  5. Enable Static File Hosting
...
  1. Select +, in the upper right corner to create a Environment Variable . For example, say "CID" as Name and "client_id" as Value from Github console, then press ADD or hit Enter.
  2. Select +, in the upper right corner to create a Environment Variable . For example, say "CSEC" as Name and "client_secret" as Value from Github console, then press ADD or hit Enter.
Not required for this example
Not required for this example
...

Following command has been used in the code module to generate logs:

                                console:log(response);

Demo

Demo

BBLANG Samples

In this section we will learn to make quick-start apps using BBLANG on BackBench.

Sending Email

In this example you will be able to send emails using backbench via Mailgun APIs.

What You'll Need:

  • Backbench account - Sign Up, the personal account will always remain free to use.
  • Mailgun account - Its free to Sign Up and you get 10000 free emails every month.
  • Codepen account - Its also free to Sign Up, or you can just fork the project to try without Sign Up too.

Backend

Prerequisites for sample app:

  1. Sign In to Backbench account.
  2. Select +, in the upper right corner to create a Bench. For example, say "SendingEmail" and select CREATE or hit Enter.

Navigate through each tabs and follow the guidelines as instructed.

...
  1. Select +, in the upper right corner to create a Module. For example, say "sendMail" and select CREATE or hit Enter.
  2. Copy and paste the code module from below.
  3. Replace YOUR_API_KEY in the pass:"key-YOUR_API_KEY" section, found in your control panel of the mailgun account.
  4. Replace the url with your API base url, found in your mailgun account or copy and paste YOUR_DOMAIN name in the url: "https://api.mailgun.net/v3/YOUR_DOMAIN/messages"
  5. Select Save.

Code module:

sendMail(message) => {

    MAILGUN_AUTH = {
        user: "api",
        pass: "key-YOUR_API_KEY"
    }

    bb:http:post({
        url: "https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",
        formData: message,
        auth: MAILGUN_AUTH
    });

}

sendMail:handler(req) => {

    message = "{{emailbody}}" % req.body

    response = sendMail({
            from: req.body.from,
            to: req.body.to,
            subject: req.body.subject,
            html: message
    })
    bb:log(response);
    return response.statusMessage;

}
Not required for this example
...
  1. Select Endpoints on the left panel and Click +, in the upper right corner to setup the HTTP endpoint.
  2. Give a Path name. For example, say /send and Click on the field under the tag Handler and select the module function to be assigned. For example, sendMail:handler, and select CREATE.
  3. /send                 sendMail:handler
  4. Enable CORS (Cross Origin Resource Sharing)
Not required for this example
Not required for this example
...

Following command has been used in the code module to generate logs:

bb:log(response);

Frontend

Change the HTTP endpoint in the JS tab as url: "https://<username>-<benchname>.backbench.io/send". Click RERUN (found at the right bottom of Codepen live demo) before submitting subsequent requests.

Sending SMS

In this example you will be able to send SMS using backbench via Twilio APIs.

What You'll Need:

  • Backbench account - Sign Up, the personal account will always remain free to use.
  • Twilio account - Its free to Sign Up and trial account would be sufficient to try this example. Twilio gives you one number for free to send text messages from. You can only text or call the pre-verified numbers. If you want to test with more numbers, you'll need to verify each one. The restriction is lifted when you upgrade the account.
  • Codepen account - Its also free to Sign Up, or you can just fork the project to try without Sign Up too.

Backend

Prerequisites for sample app:

  1. Sign In to Backbench account.
  2. Select +, in the upper right corner to create a Bench. For example, say "SendingSMS" and select CREATE or hit Enter.

Navigate through each tabs and follow the guidelines as instructed.

...
  1. Select +, in the upper right corner to create a Module. For example, say "sendSMS" and select CREATE or hit Enter.
  2. Copy and paste the code module from below.
  3. Replace AccountSid in the url: section, found in the Home Page of your Twilio console.
  4. Replace TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN in the auth: section, found in the Home Page of your Twilio console.
  5. Replace the TWILIO_NUMBER in the From: section, with your Twilio Number, found in the #Phone Numbers Page of your Twilio console.
  6. Select Save.

Code module:

sendSMS(message) -> {

    bb:log("Request ", message);
    bb:http:post({
        url: "https://api.twilio.com/2010-04-01/Accounts/AccountSid/Messages",
        auth: {
            username: "TWILIO_ACCOUNT_SID",
            password: "TWILIO_AUTH_TOKEN"
        },
        form: message
    });

}

sendSMS:handler(req) => {

    message = "{{smsbody}}" % req.body
    response = sendSMS({
        From: "TWILIO_NUMBER",
        To: req.body.to,
        Body: message
    })
    bb:log(response);
    return response.statusMessage;

}
Not required for this example
...
  1. Select Endpoints on the left panel and Click +, in the upper right corner to setup the HTTP endpoint.
  2. Give a Path name. For example, say /send and Click on the field under the tag Handler and select the module function to be assigned. For example, sendSMS:handler, and select CREATE.
  3. /send                 sendMail:handler
  4. Enable CORS (Cross Origin Resource Sharing)
Not required for this example
Not required for this example
...

Following command has been used in the code module to generate logs:

bb:log("Request ", message)
bb:log(response);

Frontend

Change the HTTP endpoint in the JS tab as url: "https://<username>-<benchname>.backbench.io/send". Click RERUN (found at the right bottom of Codepen live demo) before submitting subsequent requests.

URL Shortening App

In this example you will be able to make a URL shortening application using backbench.

Learning Outcomes:

  • Store and retrieve data from Memory.
  • Send HTTP status codes, set response headers and redirect to another URL.
  • Process request parameters.

What You'll Need:

  • Backbench account - Sign Up, the personal account will always remain free to use.
  • Codepen account - Its also free to Sign Up, or you can just fork the project to try without Sign Up too.

Backend

Prerequisites for sample app:

  1. Sign In to Backbench account.
  2. Select +, in the upper right corner to create a Bench. For example, say "minifyURL" and select CREATE or hit Enter.

Navigate through each tabs and follow the guidelines as instructed.

...
  1. Select +, in the upper right corner to create a Module. For example, say "minify" and select CREATE or hit Enter.
  2. Copy and paste the code module from below.
  3. Select Save.

Code module:

handler:minify(req, url) => {

    if (url && req.method == @GET) {

        // redirect to the original URL

        originalURL = bb:mem:get(url)

        if(originalURL) {

            // redirect
            status: 302,

            headers: {
                Location: originalURL
            },

            body: "Redirecting..."

        } else {

            // Not Found
            status: 404

        }

    } else if(req.method == @POST) {

        // create a new entry in memory

        shortURL = req.body.short_url,

        originalURL = req.body.url,

        if(shortURL != '' && originalURL != '') {

            if (bb:mem:get(req.body.short_url)) {

                // conflict
                status: 409

            } else {

                bb:mem:set(req.body.short_url, req.body.url),

                bb:log(shortURL + " : " + originalURL),

                return {
                    // created
                    status: 201
                }

            }

        } else {
            // Bad Request
            status: 400
        }


    } else {
        // Method Not Allowed
        status: 409
    }

}
...

Following command has been used in the code module to generate memory:

bb:mem:get(url)

bb:mem:get(req.body.short_url)

bb:mem:set(req.body.short_url, req.body.url)
...
  1. Select Endpoints on the left panel and Click +, in the upper right corner to setup the HTTP endpoint.
  2. Give a Path name. For example, say /:url? and Click on the field under the tag Handler and select the module function to be assigned. For example, minify:handler, and select CREATE.
  3. /:url?                 minify:handler
  4. Enable CORS (Cross Origin Resource Sharing)
Not required for this example
Not required for this example
...

Following command has been used in the code module to generate logs:

bb:log(shortURL + " : " + originalURL),

Frontend

Change the HTTP endpoint in the JS tab as url: "https://<username>-<benchname>.backbench.io/". Click RERUN (found at the right bottom of Codepen live demo) before submitting subsequent requests.

Protected Text App

In this example you will be able to design an application to store encrypted notes using backbench.

Learning Outcomes:

  • Create, Read, Update operations on Memory.
  • Process requests based on request's method and sending HTTP status codes.
  • Retrieve the data from route parameters..
  • Use of Cryptojs on frontend.

What You'll Need:

  • Backbench account - Sign Up, the personal account will always remain free to use.
  • Codepen account - Its also free to Sign Up, or you can just fork the project to try without Sign Up too.

Backend

Prerequisites for sample app:

  1. Sign In to Backbench account.
  2. Select +, in the upper right corner to create a Bench. For example, say "CryptoNotes" and select CREATE or hit Enter.

Navigate through each tabs and follow the guidelines as instructed.

...
  1. Select +, in the upper right corner to create a Module. For example, say "notes" and select CREATE or hit Enter.
  2. Copy and paste the code module from below.
  3. Select Save.

Code module:

handler:notes(req, id) => {

    if (id && req.method == @GET) {
        // retrieve the encrypted data
        data = bb:mem:get(id),
        if (data) {
            // send the encrypted data as response
            return data
        } else {
            return {
                // Not Found
                status: 404
            }
        }
    } else if (req.method == @POST) {
        // save the data
        bb:mem:set(id, req.body.data),
        return {
            // Created
            status: 201
        }
    } else {
        // Method Not Allowed
        status: 409
    }
} 
...

Following command has been used in the code module to generate memory:

data = bb:mem:get(id),

bb:mem:set(id, req.body.data),
...
  1. Select Endpoints on the left panel and Click +, in the upper right corner to setup the HTTP endpoint.
  2. Give a Path name. For example, say /:id? and Click on the field under the tag Handler and select the module function to be assigned. For example, notes:handler, and select CREATE.
  3. /:id?                 notes:handler
  4. Enable CORS (Cross Origin Resource Sharing)
Not required for this example
Not required for this example
Not required for this example

Frontend

Change the HTTP endpoint in the JS tab as url: "https://<username>-<benchname>.backbench.io/". Click RERUN (found at the right bottom of Codepen live demo) before submitting subsequent requests.

Social Share Counter App

In this example you will be able to design an api that retrieves number of shares of a specific website on popular social media platforms like facebook, google plus and linkedin.

Learning Outcomes:

  • Get request query parameters.
  • Sending multiple HTTP requests with custom header information, body, request method.
  • Sending json and different HTTP status as HTTP response.

What You'll Need:

  • Backbench account - Sign Up, the personal account will always remain free to use.
  • Codepen account - Its also free to Sign Up, or you can just fork the project to try without Sign Up too.

Backend

Prerequisites for sample app:

  1. Sign In to Backbench account.
  2. Select +, in the upper right corner to create a Bench. For example, say "socialsharecount" and select CREATE or hit Enter.

Navigate through each tabs and follow the guidelines as instructed.

...
  1. Select +, in the upper right corner to create a Module. For example, say "sharecount" and select CREATE or hit Enter.
  2. Copy and paste the code module from below.
  3. Select Save.

Code module:

getFbShareCount(url) => {
    return bb:http:get("http://graph.facebook.com/?id=" + url)
}

getLinkedinShareCount(url) => {
   return bb:http:get("http://www.linkedin.com/countserv/count/share?url=" + url + "&format=json")
}

getGoogleShareCount(url) => {
    return bb:http:req({
        method: "POST",
        uri: "https://clients6.google.com/rpc",
        headers: [ { name: 'content-type', value: 'application/json' } ],
        body: "[{\"method\":\"pos.plusones.get\", \"id\":\"p\", \"params\":{\"nolog\":\"true\",\"id\":\"" + url + "\",\"source\":\"widget\",\"userId\":\"@viewer\",\"groupId\":\"@self\"},\"jsonrpc\":\"2.0\",\"key\":\"p\",\"apiVersion\":\"v1\"}]"
    })
}

shares:handler(req) => {
    url = req.body.url,
    bb:log(req),
    fb = getFbShareCount(url),
    google = getGoogleShareCount(url),
    linkedin = getLinkedinShareCount(url),
    return {
        status: 200,
        json: {
            facebook: fb.body,
            google: google.body,
            linkedin: linkedin.body
        }
    }
} 
Not required for this example
...
  1. Select Endpoints on the left panel and Click +, in the upper right corner to setup the HTTP endpoint.
  2. Give a Path name. For example, say /shares and Click on the field under the tag Handler and select the module function to be assigned. For example, shares:handler, and select CREATE.
  3. /:id?                 notes:handler
  4. Enable CORS (Cross Origin Resource Sharing)
Not required for this example
Not required for this example
...

Following command has been used in the code module to generate logs:

bb:log(url)

Frontend

Change the HTTP endpoint in the JS tab as url: "https://<username>-<benchname>.backbench.io/shares". Click RERUN (found at the right bottom of Codepen live demo) before submitting subsequent requests.

Getting started with backbench