Example #1
0
        public Task <ServerResponse> ProcessRequest(ServerRequest request)
        {
            string         collectionName = request.Route.Parameters["collectionName"];
            DataCollection collection     = _dataSpace.GetCollection(collectionName);

            if (collection == null)
            {
                return(Deferred.Create <ServerResponse>(ServerResponse.NotFound).Task);
            }

            DataRequest dataRequest = CreateDataRequest(request, collection);

            if ((dataRequest == null) || (collection.SupportsRequest(dataRequest) == false))
            {
                return(Deferred.Create <ServerResponse>(ServerResponse.MethodNotAllowed).Task);
            }

            if ((dataRequest.Operation != DataOperation.Query) &&
                String.IsNullOrEmpty(dataRequest.Query.ID))
            {
                ServerResponse response = ServerResponse.CreateRequestError("Missing id parameter.");
                return(Deferred.Create <ServerResponse>(response).Task);
            }

            if ((dataRequest.Operation == DataOperation.Insert) ||
                (dataRequest.Operation == DataOperation.Update) ||
                (dataRequest.Operation == DataOperation.Merge))
            {
                Deferred <ServerResponse> deferred = Deferred.Create <ServerResponse>();

                request.GetData().ContinueWith(delegate(Task <object> dataTask) {
                    if (dataTask.Status == TaskStatus.Failed)
                    {
                        deferred.Reject(dataTask.Error);
                        return;
                    }

                    Task <ServerResponse> executeTask = null;
                    try {
                        dataRequest.Item = (Dictionary <string, object>)dataTask.Result;
                        executeTask      = ExecuteRequest(collection, dataRequest);
                    }
                    catch (Exception e) {
                        deferred.Resolve(ServerResponse.CreateServerError(e.Message));
                        return;
                    }

                    executeTask.ContinueWith(delegate(Task <ServerResponse> t) {
                        if (t.Status == TaskStatus.Done)
                        {
                            deferred.Resolve(t.Result);
                        }
                        else
                        {
                            deferred.Resolve(ServerResponse.CreateServerError(t.Error.Message));
                        }
                    });
                });

                return(deferred.Task);
            }
            else
            {
                return(ExecuteRequest(collection, dataRequest));
            }
        }