Created
May 28, 2018 15:21
-
-
Save tabakerov/8f461151b247c9697c6c7b770510391a to your computer and use it in GitHub Desktop.
F# with MongoDB
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Learn more about F# at http://fsharp.org | |
open System | |
open MongoDB.Driver | |
open System.Security.Authentication | |
type PostId = PostId of string | |
type CommentId = CommentId of string | |
type CommentRoot = | |
| Post of PostId | |
| Comment of CommentId | |
[CLIMutableAttribute] | |
type Comment = { | |
Id: CommentId; | |
Text: string; | |
CreatedAt: DateTime; | |
Root: CommentRoot; | |
NestedComments: List<Comment> | |
} | |
[CLIMutableAttribute] | |
type Post = { | |
Id: PostId; | |
Text: string; | |
Comments: List<Comment> | |
} | |
let newPost text = | |
let id = PostId(System.Guid.NewGuid().ToString()) | |
{Id = id; Text = text; Comments = []} | |
let addCommentToPost post commentText = | |
let id = CommentId(System.Guid.NewGuid().ToString()) | |
let comment ={Id = id; Text = commentText; CreatedAt = DateTime.UtcNow; Root = CommentRoot.Post(post.Id); NestedComments = []} | |
let newPost = {post with Comments = comment::post.Comments} | |
newPost | |
let connectToMongo connectionString = | |
let settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString)) | |
settings.SslSettings <- new SslSettings() | |
settings.SslSettings.EnabledSslProtocols <- SslProtocols.Tls12 | |
let mongoClient = new MongoClient(settings); | |
mongoClient | |
let getDatabase (client: MongoClient) (dbName: string) = | |
client.GetDatabase dbName | |
let savePost (dataBase : IMongoDatabase) (post: Post) = | |
let collection = dataBase.GetCollection("posts") | |
collection.InsertOneAsync post |> Async.AwaitTask |> Async.RunSynchronously | |
let getAllPosts (dataBase : IMongoDatabase) = | |
let filter = FilterDefinition<Post>.Empty | |
dataBase.GetCollection("posts").Find(filter).ToListAsync() |> Async.AwaitTask |> Async.RunSynchronously | |
[<EntryPoint>] | |
let main argv = | |
let connectionString = @"mongodb://turkale:[email protected]:10255/?ssl=true&replicaSet=globaldb"; | |
let client = connectToMongo connectionString | |
let db = getDatabase client "db" | |
let post = getAllPosts db | |
printfn "%A" post | |
//let post = newPost "Hello, world!" | |
//let commentedPost = addCommentToPost post "First!" | |
//let commented2 = addCommentToPost commentedPost "Second comment" | |
//savePost db commented2 |> ignore | |
printfn "Hello World from F#!" | |
0 // return an integer exit code |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment