jaune-web
Version:
85 lines (66 loc) • 2.22 kB
text/coffeescript
###*
* Source code for Json Responder
* Alvaro Juste
###
'use strict'
# 3rd
lodash = require 'lodash'
{bind} = lodash
{extend} = lodash
{isNumber} = lodash
# local
{HttpCode} = require '../http'
###*
* Respond with JSON response
* {*} [result.data] Data to be sent to client
* {Number} [result.securityCheck] Security check for request
* {Boolean} [opts.sendNotFoundOnNoData] Sends 404 on no data
###
sendData = (opts = {}) ->
result = opts.result ? .data()
data = JSON.stringify result.data ? ''
dataAvailable = !!data.length
{securityCheck} = result
{http} = .responder
{IsGrantedResult} = .engine().Security
# check if auth info to give proper response
if isNumber securityCheck
switch securityCheck
when IsGrantedResult.Yes
break
when IsGrantedResult.InsufficientTrustLevel
return http.insufficientTrustLevel.call this
else
return http.unauthorized.call this
# check if NotFound must be sent on no data
if opts.sendNotFoundOnNoData is yes and not dataAvailable
return http.notFound.call this
= data
yield {}
###*
* Respond with an error
* {Object} err The error that caused this response
###
sendError = (err) ->
engine = .engine()
isArgumentError = err instanceof engine.Error.ArgumentError
isCodedError = err instanceof engine.Error.UnhandledError
util = engine.Http.Util
errorManager = engine.Error.Manager
logger =
loggerArgs =
code = if isArgumentError then HttpCode.BadRequest else 0
unless code
code =
if isCodedError and err.code
err.code
else
HttpCode.InternalServerError
err = errorManager.asUnhandledError err # extend with more data
if logger? and loggerArgs?
yield errorManager.logErrorOnUnhandledError err, logger, extend(
loggerArgs, message: err)
util.endWithCode this, code, if isCodedError then err.message else null
module.exports = (context) ->
sendData: bind sendData, context
sendError: bind sendError, context