Setup the API:
Clone the following project on your machine (Linux or Windows).
When cloned, you have 2 options to run the API.
You have two possibilities to use this API (Linux or Windows).
- Using Docker
- Cloning the project on your machine
Using a pre configured runner (You can update values in each runner):
Windows: ./run.bat
Linux: ./run.sh
Using Dockerfile:
docker run -e MONGO_URL=mongodb://localhost/27017 -e MONGO_DB_NAME=Orizon -e APP_PORT=443 -p 443:443 bubblum/mongorest:latest
You also need to install an instance of MongoDb on your machine. This documention does not explain how to setup a MongoDb database.
Default API port is: 443
Default MongoDb connection url: mongodb://localhost:27017
Setup a Repository:
Repositories a registered automaticaly when starting the scene/project.
Create a repository from a data model:
// [JsonPropertyName("_id")] is required on your Id property, an id property is also required.
[MongoCollection( "users" )]
public record User
{
[JsonPropertyName("_id")] public string Id { get; set; }
public string Name { get; set; }
public int PermissionLevel { get; set; }
}
// Create a new database repository of type User
public sealed class UserRepository : MongoRepository<User>
{
}
Configure the API connection:
// You need to configure the MongoRest connection
// By default, the port is 443 (s&box only permit to connect to port: 80,8080,443,8443)
var system = Scene.GetSystem<MongoRestSystem>();
system.Configure( options =>
{
// The url where the API is hosted
options.Url = "https://localhost:443";
} );
Get a repository from the scene:
var users = Scene.GetRepository<UserRepository>();
CRUD Operations:
Insert:
// Insert a new user called John with a permission level 4 in the users collection
var john = new User("John", 4);
var inserted = await users.InsertAsync(john);
// Add multiples users in a same batch
var marry = new User("Marry", 2);
var inserted = await users.InsertAsync(john, marry);
Count:
// Count how many john exists in the collection
var count = await users.CountAsync(x => x.Name = "John");
Update:
// Update all users named "John" and set it's permission level to 10
var updated = await users.UpdateAsync(x => x.Name = "John", x => x.PermissionLevel = 10);
Delete:
// Delete all users named "John"
var deleted = await users.DeleteAsync(x => x.Name = "John");
Exists:
// Check if a record with the name "John" exists in the collection
var exists = await users.ExistsAsync(x => x.Name = "John");
Get:
// Get the first user called "John"
var john = (await users.GetAsync(x => x.Name = "John", 1)).FirstOrDefault();
// Get multiples users called "John" with a permission level set to 4
var johns = await users.GetAsync(x =>
{
x.Name = "John",
x.PermissionLevel = 4
});
// Get all users called "John"
var johns = await users.GetAsync(x =>
{
x.Name = "john"
});
// Get all users
var all = await users.GetAsync();
// Get all 50 first users
var all = await users.GetAsync(limit: 50);