- Go to your firebase service account settings https://console.firebase.google.com/u/0/project/{your-project-id}/settings/serviceaccounts/adminsdk
- Create and download the private key, a JSON file will be downloaded which having all configuration to connect to firestore.
- Open the file and copy all the content inside the file.
- Now convert the JSON inside the file into Base64 Encoded format string(Tip: Use any online site/local apps if you trust those).
- The encoded string will be considered as FirebaseSecret by this library.
- Now go to your local.settings.json and inside values object configure the FireabaseSecret. The key is same i.e FirebaseSecret & value is Base64 Encoded string.
[FunctionName("GetEmployee")]
public static IActionResult GetEmployee(
[HttpTrigger("get", Route = "GetEmployee/{empId}")] HttpRequest req,
[FirestoreDB("employees", DocId = "{empId}")] Employee employee)
{
return employee == null ? new NotFoundResult() : new OkObjectResult(employee);
}
[FunctionName("GetEmployee")]
public static IActionResult GetEmployee(
[HttpTrigger("get", Route = "GetEmployee")] HttpRequest req,
[FirestoreDB("employees", DocId = "{Query.empId}")] Employee employee)
{
return employee == null ? new NotFoundResult() : new OkObjectResult(employee);
}
[FunctionName("GetSeniorEmployees")]
public static async Task<IActionResult> GetSeniorEmployees(
[HttpTrigger("get", Route = "GetSeniorEmployees")] HttpRequest req,
[FirestoreDB("employees")] CollectionReference collection)
{
var employees = await collection.WhereGreaterThanOrEqualTo("Age", "40").GetDocumentsAsync<Employee>();
return new OkObjectResult(employees);
}
[FunctionName("AddSingle")]
public static IActionResult AddSingle(
[HttpTrigger("post")] Employee employee,
[FirestoreDB("employees")] out Employee outEmployee)
{
outEmployee = employee;
return new OkObjectResult(employee);
}
[FunctionName("AddBulk")]
public static async Task<IActionResult> AddBulk(
[HttpTrigger("post")] List<Employee> employees,
[FirestoreDB("employees")] IAsyncCollector<Employee> outEmployees)
{
foreach (var emp in employees)
{
await outEmployees.AddAsync(emp);
}
return new OkObjectResult("Done");
}
For output binding documents, If you want to use Id to be consider/populated wrt to doc id in firestore then follow below approach.
[FirestoreData]
public class Employee
{
//Will use this value if assigned while doc insertion, otherwise this property will be filled with docId genereated by firestore.
//If this attribute is not there for any of property in your class, then also the output binding will work.
[FirestoreDocumentId]
public string Id { get; set; }
}
For DI of firestore into your service classes
public class EmployeeService()
{
readonly FirestoreDb _db;
public EmployeeService(FirestoreDb db)
{
_db=db;
}
public List<Employee> GetAllEmployees()
{
_db.CollectionReference("Employees").GetDocumentsAsync<Employee>();
}
}