ravendb /Raven.Database/Server/Controllers/DocumentsController.cs

Language C# Lines 262
MD5 Hash b10f857c6e9380ee5c306e56391983da
Repository https://github.com/nwendel/ravendb.git View Raw File
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using Raven.Abstractions.Data;
using Raven.Abstractions.Extensions;
using Raven.Database.Extensions;
using Raven.Database.Server.WebApi.Attributes;
using Raven.Json.Linq;

namespace Raven.Database.Server.Controllers
{
	public class DocumentsController : RavenDbApiController
	{
		[HttpGet]
		[Route("docs")]
		[Route("databases/{databaseName}/docs")]
		public HttpResponseMessage DocsGet([FromUri] string id)
		{
			if (string.IsNullOrEmpty(id))
				return GetEmptyMessage(HttpStatusCode.BadRequest);
			return DocGet(id);
		}

		[HttpHead]
		[Route("docs")]
		[Route("databases/{databaseName}/docs")]
		public HttpResponseMessage DocsHead([FromUri] string id)
		{
			if (string.IsNullOrEmpty(id))
				return GetEmptyMessage(HttpStatusCode.BadRequest);
			return DocHead(id);
		}

		[HttpGet]
		[Route("docs")]
		[Route("databases/{databaseName}/docs")]
		public HttpResponseMessage DocsGet()
		{
		    using (var cts = new CancellationTokenSource())
		    using (cts.TimeoutAfter(DatabasesLandlord.SystemConfiguration.DatabaseOperationTimeout))
		    {
		        long documentsCount = 0;
		        var lastDocEtag = Etag.Empty;
		        Database.TransactionalStorage.Batch(
		            accessor =>
		            {
		                lastDocEtag = accessor.Staleness.GetMostRecentDocumentEtag();
		                documentsCount = accessor.Documents.GetDocumentsCount();
		            });

		        lastDocEtag = lastDocEtag.HashWith(BitConverter.GetBytes(documentsCount));
		        if (MatchEtag(lastDocEtag)) return GetEmptyMessage(HttpStatusCode.NotModified);

		        var startsWith = GetQueryStringValue("startsWith");
		        HttpResponseMessage msg;
		        int nextPageStart = GetNextPageStart();
			    if (string.IsNullOrEmpty(startsWith))
			    {
				    var results = Database.Documents.GetDocuments(GetStart(), GetPageSize(Database.Configuration.MaxPageSize), 
						GetEtagFromQueryString(), cts.Token);
				    msg = GetMessageWithObject(results);
			    }
			    else
			    {
				    var transformer = GetQueryStringValue("transformer");
				    var transformerParameters = this.ExtractTransformerParameters();

				    msg =
					    GetMessageWithObject(
						    Database.Documents.GetDocumentsWithIdStartingWith(
							    startsWith,
							    GetQueryStringValue("matches"),
							    GetQueryStringValue("exclude"),
							    GetStart(),
							    GetPageSize(Database.Configuration.MaxPageSize),
							    cts.Token,
							    ref nextPageStart, transformer, transformerParameters,
								skipAfter: GetQueryStringValue("skipAfter")));
			    }

			    WriteHeaders(new RavenJObject { { Constants.NextPageStart, nextPageStart } }, lastDocEtag, msg);

		        return msg;
		    }
		}

		[HttpPost]
		[Route("docs")]
		[Route("databases/{databaseName}/docs")]
		public async Task<HttpResponseMessage> DocsPost()
		{
			var json = await ReadJsonAsync();
			var id = Database.Documents.Put(null, Etag.Empty, json,
								  InnerHeaders.FilterHeadersToObject(),
								  GetRequestTransaction());

			return GetMessageWithObject(id);
		}

		[HttpHead]
		[Route("docs/{*docId}")]
		[Route("databases/{databaseName}/docs/{*docId}")]
		public HttpResponseMessage DocHead(string docId)
		{
			var msg = GetEmptyMessage();
			msg.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json") { CharSet = "utf-8" };
			var transactionInformation = GetRequestTransaction();
			var documentMetadata = Database.Documents.GetDocumentMetadata(docId, transactionInformation);
			if (documentMetadata == null)
			{
				msg.StatusCode = HttpStatusCode.NotFound;
				return msg;
			}

			Debug.Assert(documentMetadata.Etag != null);
			if (MatchEtag(documentMetadata.Etag) && documentMetadata.NonAuthoritativeInformation == false)
			{
				msg.StatusCode = HttpStatusCode.NotModified;
				return msg;
			}

			if (documentMetadata.NonAuthoritativeInformation != null && documentMetadata.NonAuthoritativeInformation.Value)
				msg.StatusCode = HttpStatusCode.NonAuthoritativeInformation;

			documentMetadata.Metadata[Constants.DocumentIdFieldName] = documentMetadata.Key;
			documentMetadata.Metadata[Constants.LastModified] = documentMetadata.LastModified; //HACK ? to get the document's last modified value into the response headers

			WriteHeaders(documentMetadata.Metadata, documentMetadata.Etag, msg);

			return msg;
		}

		[HttpGet]
		[Route("docs/{*docId}")]
		[Route("databases/{databaseName}/docs/{*docId}")]
		public HttpResponseMessage DocGet(string docId)
		{
			var msg = GetEmptyMessage();
			if (string.IsNullOrEmpty(GetHeader("If-None-Match")))
				return GetDocumentDirectly(docId, msg);

			Database.TransactionalStorage.Batch(
				_ => // we are running this here to ensure transactional safety for the two operations
				{
					var transactionInformation = GetRequestTransaction();
					var documentMetadata = Database.Documents.GetDocumentMetadata(docId, transactionInformation);
					if (documentMetadata == null)
					{
						msg = GetEmptyMessage(HttpStatusCode.NotFound);
						return;
					}
					Debug.Assert(documentMetadata.Etag != null);
					if (MatchEtag(documentMetadata.Etag) && documentMetadata.NonAuthoritativeInformation != true)
					{
						msg.StatusCode = HttpStatusCode.NotModified;
						return;
					}
					if (documentMetadata.NonAuthoritativeInformation != null && documentMetadata.NonAuthoritativeInformation.Value)
						msg.StatusCode = HttpStatusCode.NonAuthoritativeInformation;

					msg = GetDocumentDirectly(docId, msg);
				});

			return msg;
		}

		[HttpDelete]
		[Route("docs/{*docId}")]
		[Route("databases/{databaseName}/docs/{*docId}")]
		public HttpResponseMessage DocDelete(string docId)
		{
			Database.Documents.Delete(docId, GetEtag(), GetRequestTransaction());
			return GetEmptyMessage(HttpStatusCode.NoContent);
		}

		[HttpPut]
		[Route("docs/{*docId}")]
		[Route("databases/{databaseName}/docs/{*docId}")]
		public async Task<HttpResponseMessage> DocPut(string docId)
		{
			var json = await ReadJsonAsync();
			var putResult = Database.Documents.Put(docId, GetEtag(), json, InnerHeaders.FilterHeadersToObject(), GetRequestTransaction());
			return GetMessageWithObject(putResult, HttpStatusCode.Created);
		}

		[HttpPatch]
		[Route("docs/{*docId}")]
		[Route("databases/{databaseName}/docs/{*docId}")]
		public async Task<HttpResponseMessage> DocPatch(string docId)
		{
			var patchRequestJson = await ReadJsonArrayAsync();
			var patchRequests = patchRequestJson.Cast<RavenJObject>().Select(PatchRequest.FromJson).ToArray();
			var patchResult = Database.Patches.ApplyPatch(docId, GetEtag(), patchRequests, GetRequestTransaction());
			return ProcessPatchResult(docId, patchResult.PatchResult, null, null);
		}

		[HttpEval]
		[Route("docs/{*docId}")]
		[Route("databases/{databaseName}/docs/{*docId}")]
		public async Task<HttpResponseMessage> DocEval(string docId)
		{
			var advPatchRequestJson = await ReadJsonObjectAsync<RavenJObject>();
			var advPatch = ScriptedPatchRequest.FromJson(advPatchRequestJson);
			bool testOnly;
			bool.TryParse(GetQueryStringValue("test"), out testOnly);
			var advPatchResult = Database.Patches.ApplyPatch(docId, GetEtag(), advPatch, GetRequestTransaction(), testOnly);
			return ProcessPatchResult(docId, advPatchResult.Item1.PatchResult, advPatchResult.Item2, advPatchResult.Item1.Document);
		}

		private HttpResponseMessage GetDocumentDirectly(string docId, HttpResponseMessage msg)
		{
			if (Database == null)
			{
				msg.StatusCode = HttpStatusCode.NotFound;
				return msg;
			}
			var doc = Database.Documents.Get(docId, GetRequestTransaction());
			if (doc == null)
			{
				msg.StatusCode = HttpStatusCode.NotFound;
				return msg;
			}

			if (doc.NonAuthoritativeInformation != null && doc.NonAuthoritativeInformation.Value)
				msg.StatusCode = HttpStatusCode.NonAuthoritativeInformation;

			Debug.Assert(doc.Etag != null);
			doc.Metadata[Constants.LastModified] = doc.LastModified;
			doc.Metadata[Constants.DocumentIdFieldName] = Uri.EscapeUriString(doc.Key ?? string.Empty);
			msg.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json") { CharSet = "utf-8" };
			return WriteData(doc.DataAsJson, doc.Metadata, doc.Etag, msg: msg);
		}

		private HttpResponseMessage ProcessPatchResult(string docId, PatchResult patchResult, object debug, RavenJObject document)
		{
			switch (patchResult)
			{
				case PatchResult.DocumentDoesNotExists:
					return GetEmptyMessage(HttpStatusCode.NotFound);
				case PatchResult.Patched:
					var msg = GetMessageWithObject(new { Patched = true, Debug = debug });
					msg.Headers.Location = Database.Configuration.GetFullUrl("docs/" + docId);
					return msg;
				case PatchResult.Tested:
					return GetMessageWithObject(new
					{
						Patched = false,
						Debug = debug,
						Document = document
					});
				default:
					throw new ArgumentOutOfRangeException("Value " + patchResult + " is not understood");
			}
		}
	}
}
Back to Top