# -*- coding: utf-8 -*-

"""\
© Copyright. All rights reserved.

"""

from __future__ import unicode_literals

import json
try:
    from json.decoder import JSONDecodeError  # python 3
except ImportError:
    JSONDecodeError = ValueError  # python 2
import logging

import falcon


LOG = logging.getLogger(__name__)


def json_body(req, *_):
    """Decode JSON request body and attach to request as `body`."""
    body = req.bounded_stream.read().decode('utf-8')
    try:
        req.body = json.loads(body) if body else {}
    except JSONDecodeError as ex:
        raise falcon.HTTPBadRequest(
            code='BAD_JSON',
            description=str(ex))
