Source

infohub/Catalogue.js

// $Id$
// @ts-check

'use strict';

import { RestServices } from '../tools/RestServices.js';
import { ApiResponse } from '../tools/ApiResponse.js';
import { Context } from './Context.js';
import { cnObject } from '../gom/cnObject.js';

/**
 *
 *  @category COLNEO infohub
 *
 *  @classdesc Catalogue on infohub
 *
 */
export class Catalogue extends cnObject {

   static className = "Catalogue";

  /**
   *  Since scope information is retrieved from COLNEO infohub, this constructor is not
   *  called directly. Use factory method `ProjectServices.getProjectById()` or `ProjectServices.getProjectByShortId()` instead.
   *
   * @since 09.2025, jh
   */
  constructor() {
    super();
  }

}

/**
 *
 *  @category COLNEO infohub
 *
 */
export class CatalogueServices {
     
  _ctx = null

  /**
   * @since 1.0, 09.2025, jh
   * @param {Context} ctx - Context instance
   *
   */
  constructor(ctx) {
    this._ctx = ctx;
  }

  /**
   * 
   * @param {*} cat_data 
   * @returns {Promise<Function>} Callback function
   */
  async createCatalogue( cat_data , cb ) {

    console.log('### <CatalogueServices.createCatalogue()>')

    console.log( JSON.stringify(cat_data) )
    
    const url = `${this._ctx.getServiceUrl(Context.SERVICE.HUB)}/${this._ctx.getScope()}/catalogues`;

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /* RestResponse */ const resp = await RestServices.makeApiCall(this._ctx.getToken(), RestServices.METHODS.POST, url, cat_data )
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    // resp.dump("RETURN CREATE OBJECT")

    if( resp.status < 300 ) {

      let obj = new cnObject()
      obj.setFromJson( resp.data )

      return cb(new ApiResponse(resp.status, obj))

    } else {

      return cb(resp)

    }

  }

  /**
   * 
   * Get catalogue by ID. 
   * If catalogue does not exist and cat_data is given, a new catalogu is created using cat_data
   * @param {*} cat_id 
   * @param {*} query = {
   *    'members'     : 
   *    'properties'  :
   *    'nodes'       :
   * }
   * @param {*} cb 
   * @param {*} cat_data 
   * @returns {Promise<Function>} Callback function
   */
  async getCatalogue( cat_id, query , cb , cat_data = null ) {
 
    console.log( '### <CatalogueServices.getCatalogue()> ')

    const urlParams = new URLSearchParams();
          
    let f = `( $object_id ~eq~ '${cat_id}' )`;
    urlParams.set('filter', f);
    
    for ( const m in query ) {
      urlParams.set( m , query[m] );
    }

    const q = `?${urlParams.toString()}`;

    let path_endpoint = `${this._ctx.getServiceUrl(Context.SERVICE.HUB)}/${this._ctx.getScope()}/catalogues${q}`;

    //////////////////////////////////////////////////////////////////////////////////////////////////////////
    let resp = await RestServices.makeApiCall(this._ctx.getToken(), RestServices.METHODS.GET, path_endpoint);
    //////////////////////////////////////////////////////////////////////////////////////////////////////////
    
    resp.dump("CATALOGUE");

    const arr = Array.isArray(resp.data) ? resp.data : [];
    
    if (resp.status < 300) {

      console.log( `len : ${arr.length}` )

      if (arr.length > 0) {

        let obj = new Catalogue();
        obj.setFromJson(arr[0]);

        return cb(new ApiResponse(resp.status, obj));

      } else {

        if (cat_data) {
          
          this.createCatalogue(cat_data, (ret) => {
            return cb(ret);
          })

        } else {
          return cb(new ApiResponse(404, null));
        }

      }

    } else {

      return cb(resp);

    }

  }
  
  /**
   *
   * @param {*} project_sid
   * @param {*} cb
   * @param {*} query
   */
  getCatalogueByShortId(project_sid, cb, query = { members: ['info'] } ) {
    // GET /{scope}/nodes/{node}/data

    if(!this._ctx.getScope() || this._ctx.getScope() === ''){
      return cb(new ApiResponse(404, null, 'Scope not set in context'));
    }
    if(!project_sid || project_sid === ''){
      return cb(new ApiResponse(404, null, 'Project short ID not set'));
    }

    let q = '';

    if (query && Object.keys(query).length > 0) {
      const urlParams = new URLSearchParams();
      for (const key of Object.keys(query)) {
        urlParams.set(key, query[key]);
      }
      q = `?${urlParams.toString()}`;
    }

    let path_endpoint = `${this._ctx.getServiceUrl(Context.SERVICE.HUB)}/${this._ctx.getScope()}/nodes/${project_sid}/data${q}`;

    // RestServices.makeApiCall returns a Promise
    RestServices.makeApiCall(this._ctx.getToken(), RestServices.METHODS.GET, path_endpoint)
      .then((resp) => {
        // resp.dump("PROJECT");

        if (resp.status < 300) {
          let obj = new Catalogue();
          obj.setFromJson(resp.data);
          // console.log("PROJECT___", JSON.stringify(obj.getAsJson() ) )
          return cb(new ApiResponse(resp.status, obj));
        } else {
          return cb(resp);
        }
      })
      .catch((error) => {
        console.error('Error in getCatalogueByShortId:', error);
        return cb(new ApiResponse(500, null, error.message || 'Unknown error'));
      });
  }

  /**
   *  Get list of catalogues.
   *
   *  @param {*} cb    callback
   *  @param {*} query optional query filter
   */
  async getCatalogueList( cb , query = null) {

    // GET /{scope}/nodes/{node}/data

    let q = '';

    if (query && Object.keys(query).length > 0) {
      const urlParams = new URLSearchParams();
      for (const key of Object.keys(query)) {
        urlParams.set(key, query[key]);
      }
      q = `?${urlParams.toString()}`;
    }

    let path_endpoint = `${this._ctx.getServiceUrl(Context.SERVICE.HUB)}/${this._ctx.getScope()}/catalogues${q}`;

    let resp = await RestServices.makeApiCall(this._ctx.getToken(), RestServices.METHODS.GET, path_endpoint);
    // resp.dump("PROJECT LIST");

    return cb(resp);

  }

}