/**
 * koa middleware to support rest.
 * 
 * Usage:
 * 
 *   const restify = require('./restify');
 *   app.use(restify('/api/'));
 * 
 * Controllers:
 * 
 *   async function (ctx, next) {
 *     return ctx.rest({
 *       id: 12345,
 *       name: 'Michael'
 *     });
 *   }
 */

function _logJSON(data) {
    if (data) {
        logger.debug(JSON.stringify(data, function (key, value) {
            if (key === 'image' && value) {
                return value.substring(0, 20) + ' (' + value.length + ' bytes image data) ...';
            }
            return value;
        }, '  '));
    }
    else {
        logger.debug('(EMPTY)');
    }
}

module.exports = function (pathPrefix = '/api/') {
    return async (ctx, next) => {
        if (ctx.request.path.startsWith(pathPrefix)) {
            logger.info(`process API ${ctx.request.method} ${ctx.request.url}...`);
            ctx.validate = (schemaName) => {
                // todo: validate schema:
            };
            ctx.rest = (data) => {
                ctx.response.type = 'application/json';
                ctx.response.body = data;
            }
            try {
                await next();
            } catch (e) {
                logger.warn('process API error.', e);
                ctx.response.status = 400;
                ctx.response.type = 'application/json';
                ctx.response.body = {
                    error: e.error || 'internal:unknown_error',
                    message: e.message || ''
                };
            }
        } else {
            await next();
        }
    };
};

@@ -276,16 +276,101 @@
  %7D%0A */%0A%0A
+const%0A    logger = require('../logger'),%0A    api_schema = require('../api_schema');%0A%0A
 function
@@ -824,16 +824,96 @@
     
+let%0A            request = ctx.request,%0A            response = ctx.response;%0A        
 if (
-ctx.
 requ
@@ -986,20 +986,16 @@
 s API $%7B
-ctx.
 request.
@@ -1004,20 +1004,16 @@
 thod%7D $%7B
-ctx.
 request.
@@ -1088,25 +1088,27 @@
     
-// todo: 
+api_schema.
 validate
  sch
@@ -1107,16 +1107,35 @@
 date
- 
+(
 schema
-:
+Name, request.body);
 %0A   
@@ -1189,36 +1189,32 @@
                 
-ctx.
 response.type = 
@@ -1241,36 +1241,32 @@
                 
-ctx.
 response.body = 
@@ -1421,36 +1421,32 @@
                 
-ctx.
 response.status 
@@ -1460,36 +1460,32 @@
                 
-ctx.
 response.type = 
@@ -1520,20 +1520,16 @@
         
-ctx.
 response

add ctx.validate()