/* Copyright 2010-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver.Core.Misc;
namespace MongoDB.Driver
{
///
/// Base class for an index keys definition.
///
/// The type of the document.
public abstract class IndexKeysDefinition
{
///
/// Renders the index keys definition to a .
///
/// The document serializer.
/// The serializer registry.
/// A .
public abstract BsonDocument Render(IBsonSerializer documentSerializer, IBsonSerializerRegistry serializerRegistry);
///
/// Performs an implicit conversion from to .
///
/// The document.
///
/// The result of the conversion.
///
public static implicit operator IndexKeysDefinition(BsonDocument document)
{
if (document == null)
{
return null;
}
return new BsonDocumentIndexKeysDefinition(document);
}
///
/// Performs an implicit conversion from to .
///
/// The JSON string.
///
/// The result of the conversion.
///
public static implicit operator IndexKeysDefinition(string json)
{
if (json == null)
{
return null;
}
return new JsonIndexKeysDefinition(json);
}
}
///
/// A based index keys definition.
///
/// The type of the document.
public sealed class BsonDocumentIndexKeysDefinition : IndexKeysDefinition
{
private readonly BsonDocument _document;
///
/// Initializes a new instance of the class.
///
/// The document.
public BsonDocumentIndexKeysDefinition(BsonDocument document)
{
_document = Ensure.IsNotNull(document, nameof(document));
}
///
/// Gets the document.
///
public BsonDocument Document
{
get { return _document; }
}
///
public override BsonDocument Render(IBsonSerializer documentSerializer, IBsonSerializerRegistry serializerRegistry)
{
return _document;
}
}
///
/// A JSON based index keys definition.
///
/// The type of the document.
public sealed class JsonIndexKeysDefinition : IndexKeysDefinition
{
private readonly string _json;
///
/// Initializes a new instance of the class.
///
/// The json.
public JsonIndexKeysDefinition(string json)
{
_json = Ensure.IsNotNull(json, nameof(json));
}
///
/// Gets the json.
///
public string Json
{
get { return _json; }
}
///
public override BsonDocument Render(IBsonSerializer documentSerializer, IBsonSerializerRegistry serializerRegistry)
{
return BsonDocument.Parse(_json);
}
}
}