Create custom endpoint for aggregate

This commit is contained in:
IgorKalaidjan 2018-11-15 13:12:20 +02:00
parent 96932793b1
commit 64dad7f7c7
3 changed files with 72 additions and 0 deletions

View File

@ -0,0 +1,8 @@
"""Tatau Query implementation for MongoDB"""
def aggregate(conn, pipeline, table='transactions'):
cursor = conn.run(
conn.collection(table).aggregate(pipeline))
return (obj for obj in cursor)

View File

@ -12,6 +12,7 @@ from bigchaindb.web.views import (
transactions as tx, transactions as tx,
outputs, outputs,
validators, validators,
aggregate,
) )
@ -40,8 +41,12 @@ ROUTES_API_V1 = [
r('validators/', validators.ValidatorsApi), r('validators/', validators.ValidatorsApi),
] ]
ROUTES_API_TATAU = [
r('aggregate/', aggregate.AggregateListApi),
]
API_SECTIONS = [ API_SECTIONS = [
(None, [r('/', info.RootIndex)]), (None, [r('/', info.RootIndex)]),
('/api/v1/', ROUTES_API_V1), ('/api/v1/', ROUTES_API_V1),
('/api/tatau/', ROUTES_API_TATAU),
] ]

View File

@ -0,0 +1,59 @@
# Tatau
"""This module provides the blueprint for some basic API endpoints.
For more information please refer to the documentation: http://bigchaindb.com/http-api
"""
import logging
import types
import json
from bson import json_util
from flask_restful import Resource
from flask import request, current_app
from bigchaindb.backend.exceptions import OperationError
from bigchaindb.web.views.base import make_error
from bigchaindb.tatau_backend import query
logger = logging.getLogger(__name__)
class AggregateListApi(Resource):
def post(self):
"""API endpoint to aggregate.
Args:
pipeline (str): Request of aggregate in body.
Return:
A list of aggregate the query.
"""
table = request.args.get('table')
if not table:
table = 'transactions'
# return make_error(400, 'table cannot be empty')
try:
pipeline = request.get_json(force=True)
except Exception as e:
return make_error(400, 'Json required')
pool = current_app.config['bigchain_pool']
with pool() as bigchain:
def aggregate(obj, pipeline, table):
return query.aggregate(obj.connection, pipeline, table)
bigchain.aggregate = types.MethodType(aggregate, bigchain)
data = bigchain.aggregate(pipeline, table)
try:
return json.loads(json_util.dumps(data))
except OperationError as e:
return make_error(
400,
'({}): {}'.format(type(e).__name__, e)
)