async Task SetUpAsync() { Func <string, string, string> Env = (name, @default) => Environment.GetEnvironmentVariable(name) ?? @default; var domain = Env("FAUNA_DOMAIN", "localhost"); var scheme = Env("FAUNA_SCHEME", "http"); var port = Env("FAUNA_PORT", "8443"); var secret = Env("FAUNA_ROOT_KEY", "secret"); var endpoint = $"{scheme}://{domain}:{port}"; rootClient = new FaunaClient(secret: secret, endpoint: endpoint); const string dbName = "faunadb-csharp-test"; DbRef = Database(dbName); try { await rootClient.Query(Delete(DbRef)); } catch (BadRequest) {} await rootClient.Query(CreateDatabase(Obj("name", dbName))); clientKey = await rootClient.Query(CreateKey(Obj("database", DbRef, "role", "server"))); adminKey = await rootClient.Query(CreateKey(Obj("database", DbRef, "role", "admin"))); client = rootClient.NewSessionClient(clientKey.Get(SECRET_FIELD)); adminClient = rootClient.NewSessionClient(adminKey.Get(SECRET_FIELD)); }
public async Task <List <Message> > Get(string countryCode, string licensePlate) { var index = Language.Index("MessageIndex"); var match = Language.Match(index, countryCode, licensePlate); var result = await _client.Query(Language.Paginate(match)); var data = result.At("data").To <Value[]>(); var list = new List <Message>(); data.Match( Success: values => list.AddRange(values.Select(v => MessageConverter.Convert(v))), Failure: reason => { // TODO: do some logging here } ); list.ForEach(m => { m.LicensePlate = licensePlate; m.CountryCode = countryCode; }); return(list); }
static async Task <FaunaClient> CreateNewDatabase(FaunaClient client, string name) { await client.Query(CreateDatabase(Obj("name", name))); var key = await client.Query(CreateKey(Obj("database", Database(name), "role", "admin"))); return(client.NewSessionClient(secret: key.Get(SECRET_FIELD))); }
public async Task CreateToken(string userId, string token) { await _client.Query( If(Exists(Match(Index("auth_id"), userId)), Foreach(Paginate(Match(Index("auth_id"), userId)), @ref => Update(@ref, Obj("UserId", userId, "Token", token))), Create(Class("auth_cache"), Obj("UserId", userId, "Token", token)) ) ); }
public async Task <User> FindByIdentifier(string identifier) { var result = await _client.Query(Get( Union( Match(Index("user_username"), identifier), Match(Index("user_email"), identifier) ) )); return(result.Get(Field.At("data")).To <User>().Value); }
void AssertQueryException <TException>(FaunaClient client, Expr query, string code, string description, IReadOnlyList <string> position = null) where TException : FaunaException { var exception = Assert.ThrowsAsync <TException>(async() => await client.Query(query)); AssertException(exception, code, description, position); }
[Test] public async Task TestAuthenticateSession() { Value createdInstance = await client.Query( Create(await RandomClass(), Obj("credentials", Obj("password", "abcdefg"))) ); Value auth = await client.Query( Login( createdInstance.Get(REF_FIELD), Obj("password", "abcdefg")) ); FaunaClient sessionClient = GetClient(secret: auth.Get(SECRET_FIELD)); Value loggedOut = await sessionClient.Query(Logout(true)); Assert.AreEqual(true, loggedOut.To <bool>().Value); Value identified = await client.Query( Identify(createdInstance.Get(REF_FIELD), "wrong-password") ); Assert.AreEqual(false, identified.To <bool>().Value); }
private void Execute( string indexName, string collectionName, string fieldName, string serverKey) { var client = new FaunaClient(serverKey); try { var result = client .Query(CreateIndex(Obj( "name", indexName, "source", Collection(collectionName), "terms", Arr(Obj("field", Arr("data", fieldName))) ))) .GetAwaiter() .GetResult(); Console.WriteLine(result); } catch (Exception exception) { Console.WriteLine(exception.Message); } }
Task <Value> RetrieveNextPage(Expr cursor, bool reverse) { Expr _after = null; Expr _before = null; if (cursor != null) { if (reverse) { _before = cursor; } else { _after = cursor; } } var q = Language.Paginate(set, ts, _after, _before, size, events, sources); foreach (var lambda in faunaFunctions) { q = lambda(q); } return(client.Query(q)); }
public async Task <OpResult <Gramercy> > SaveGramercyAsync(Gramercy gramercy, Value gramercyValue = null, bool isUpdate = false) { OpResult <Gramercy> result = new OpResult <Gramercy>(); try { if (isUpdate) { await _faunaClient.Query( Update( gramercyValue.At("ref"), Obj("data", Encoder.Encode(gramercy)) ) ); } else { await _faunaClient.Query( Create( Ref("classes/gramercy"), Obj("data", Encoder.Encode(gramercy)) ) ); } result.Result = gramercy; } catch (Exception ex) { result.FromException(ex); } return(result); }
private async Task <bool> FillCategoryReference(string category, FaunaClient client) { var categoryReference = await client.Query(Get(Ref( Collection("Categories"), category ))); InCategoryId = categoryReference.At("ref") as RefV; return(true); }
protected async Task <RefV> RandomCollection() { Value coll = await client.Query( CreateCollection( Obj("name", RandomStartingWith("some_coll_"))) ); return(GetRef(coll)); }
public static async Task GetVectorPronunciation(FaunaClient client, string twitchdisplayname) { Value result = await client.Query( Get( Match(Index("vectorprounciation_get_twitch_user"), twitchdisplayname))); TwitchUsers twitchusers = Decoder.Decode <TwitchUsers>(result.At("data")); Console.WriteLine("{0} : {1}", twitchusers.VectorProronunciation, twitchusers.TwitchDisplayName); }
public void TestServerTimingOut() { Stopwatch watch = new Stopwatch(); watch.Start(); Task <Value> task0 = client.Query(Now()); Assert.ThrowsAsync <TimeoutException>(async() => await task0); watch.Stop(); Assert.IsTrue(task0.IsCompleted, "the task0 is completed"); Assert.IsTrue(task0.IsFaulted, "the task0 failed"); StringAssert.Contains("The operation has timed out.", task0.Exception.Message); Assert.IsTrue(watch.Elapsed.TotalSeconds >= 10 && watch.Elapsed.TotalSeconds <= 12); }
public bool AddHealthCheck(HealthCheck healthCheck) { try { var healtCheckDataItems = healthCheck.DataItems; var faunaHealthCheck = _client.Query( Create( Collection("healthchecks"), Obj("data", Obj( "date", healthCheck.Date, "serverId", healthCheck.ServerId, "responseTime", healthCheck.ResponseTime ) ) ) ).Result; foreach (var healthCheckDataItem in healtCheckDataItems) { var _ = _client.Query( Create( Collection("dataItems"), Obj("data", Obj( "healthcheck", faunaHealthCheck.At("ref"), "name", healthCheckDataItem.Name, "data", healthCheckDataItem.Data ) ) ) ).Result; } return(true); } catch (Exception e) { Logger.Error(e); return(false); } }
public static async Task WriteLink(FaunaClient client, string capturedlink) { Links link = new Links(DateTime.UtcNow, capturedlink); await client.Query( Create( Collection("links"), Obj("data", Encoder.Encode(link)) ) ); }
public async Task <Artist> GetArtistAsync(string id) { var value = await _faunaClient .Query(Get(Ref(Collection(Collection), id))); return(DecodeArtist(value)); }
private async Task <List <Product> > GetProducts(Value[] values, FaunaClient client) { List <Product> products = new List <Product>(); foreach (Value value in values) { var product = Decoder.Decode <Product>(value.At("data")); product.Id = (value.At("ref") as RefV).Id; product.CategoryId = (value.At("data").At("category") as RefV).Id; var cat = await client.Query(Get(Ref(Collection(CATEGORY_COLLECTION_NAME), product.CategoryId))); product.CategoryName = cat.At("data").At("name").To <string>().Value; products.Add(product); } return(products); }
private void Execute(string collectionName, string serverKey) { var client = new FaunaClient(serverKey); try { var result = client .Query( CreateCollection(Obj("name", collectionName)), TimeSpan.FromSeconds(30)) .GetAwaiter() .GetResult(); Console.WriteLine(result); } catch (Exception exception) { Console.WriteLine(exception.Message); } }
public async Task Create(Type collectionType, FaunaClient client) { FaunaCollection collection = collectionType.GetCustomAttribute <FaunaCollection>(); var options = new Dictionary <string, Expr>(); if (!string.IsNullOrEmpty(this.Name)) { options.Add("name", this.Name); } else { options.Add("name", GenerateIndexName(collectionType)); } options.Add("source", Collection(collection?.Name ?? collectionType.Name)); if (Terms != null && Terms.Length > 0) { options.Add("terms", GenerateTermsObj(collectionType)); } if (Values != null && Values.Length > 0) { options.Add("values", GenerateValuesObj(collectionType)); } if (this.Data != null) { options.Add("data", Obj(JsonConvert.DeserializeObject <Dictionary <string, Expr> >(Data))); } if (this.Permissions != null) { options.Add("permissions", Obj(JsonConvert.DeserializeObject <Dictionary <string, Expr> >(Permissions))); } options.Add("unique", this.Unique); options.Add("serialized", this.Serialized); await client.Query(CreateIndex(options)); }
public static async Task CreateDatabaseSchema(FaunaClient client, List <Type> types, bool onlyDecoratedChildren = true) { foreach (Type type in types) { System.Diagnostics.Debug.WriteLine("Creating fauna collection for " + type.Name + "..."); await client.Query(CreateCollection(type)); System.Diagnostics.Debug.WriteLine("created"); var indexAttributes = type.GetCustomAttributes <FaunaIndex>(); if (indexAttributes != null) { foreach (FaunaIndex index in indexAttributes) { System.Diagnostics.Debug.WriteLine("Creating fauna index for " + type.Name + "..."); if (index != null) { await index.Create(type, client); } } } } }
public static async Task GetVectorPronunciationAll(FaunaClient client) { Value value = await client.Query(Paginate(Match(Index("vpronunciation")))); TwitchUsers twitchUsers = value.At("data").To <TwitchUsers>().Value; Console.WriteLine(" loaded: {0}", twitchUsers.VectorProronunciation); //Value result = await client.Query( // Get( // Match(Index("vpronunciation")))); //IResult<Value> data = result.At("data").To<Value>(); //data.Match( // Success: value => ProcessData(value), // Failure: reason => Console.WriteLine($"Something went wrong: {reason}") //); //TwitchUsers twitchusers = (TwitchUsers)result.At("data").To<TwitchUsers>(); //Console.WriteLine(twitchusers.TwitchDisplayName); }
[Test] public async Task TestCreateDatabase() { await adminClient.Query(CreateDatabase(Obj("name", "database_for_test"))); Assert.AreEqual(BooleanV.True, await adminClient.Query(Exists(Database("database_for_test")))); }
public Task <Value> Query(Expr query) { return(_client.Query(query)); }
async Task TearDownAsync() { await rootClient.Query(Delete(DbRef)); }