Blog>
Snippets

Angular Service with N1QL Queries for Dynamic Filtering

Create a service in Angular that performs dynamic filtering using N1QL queries to fetch data from Couchbase based on user input.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class CouchbaseDataService {
  private readonly apiUrl = 'http://your-couchbase-server.com/query';

  constructor(private http: HttpClient) {}

  // Function to perform dynamic filtering with N1QL queries
  getFilteredData(filters) {
    // Construct the N1QL query based on the filters
    // Example: SELECT * FROM `bucket-name` WHERE type = $type AND price < $maxPrice
    let n1qlQuery = 'SELECT * FROM `bucket-name`';
    let queryParams = {};
    let whereClauses = [];

    Object.keys(filters).forEach(key => {
      queryParams[key] = filters[key];
      whereClauses.push(`${key} = $${key}`);
    });

    if (whereClauses.length) {
      n1qlQuery += ' WHERE ' + whereClauses.join(' AND ');
    }

    const requestOptions = {
      method: 'POST',
      body: JSON.stringify({
        statement: n1qlQuery,
        args: queryParams,
      }),
      headers: {
        'Content-Type': 'application/json'
      }
    };

    return this.http.post(this.apiUrl, requestOptions);
  }
}
This Angular service named 'CouchbaseDataService' includes a method 'getFilteredData' to execute dynamic N1QL queries against a Couchbase server. The method constructs the query based on provided filters, compiles parameters for the placeholders, and performs a POST request with the constructed query to the Couchbase REST API. It expects a base API URL pointed to the Couchbase query service and uses Angular's HttpClient for the API request.