Querying Object Service Programmatically

I’m currently writing a typescript function to execute a particular ontology search based on the input paramter. I want to write a function that behaves like the following, but having a bit of trouble getting the objectSetFilter object to accept a particular attribute programmatically.

The code snippet below describes what I’m trying to tackle!

function getAttribute(
desiredAttr: string,
desiredValue: string,
): Promise<DesiredObjectType> {
const desiredObjects = Objects.search().DesiredObjects().filter(obj => obj.desiredAttr.exactMatch(desiredValue))
return desiredObjects
}```
1 Like

Hi @stevengh, as written, your return type should be ObjectSet<DesiredObject> instead of a Promise.

Apart from that, what error are you getting?

You should be able to dynamically query an object type property using a variable as follow:

Objects.search().DesiredObjects().filter(obj => (obj as any)[desiredAttr].exactMatch(desiredValue));

Additionally, I find the function bellow can be useful to check that desiredAttr is valid:

import { UserFacingError } from "@foundry/functions-api";
import { ObjectType } from "@foundry/ontology-api";

export class Utils { 

    public static checkPropertyApiNameIsValid(propertyApiName: string, objectType: ObjectType): void {
        const allPropertyApiNames = Object.values(objectType.properties).map(property => property.apiName);
        if (!allPropertyApiNames.includes(propertyApiName)) {
            throw new UserFacingError(`"${propertyApiName}" is not a valid property API name for object type ${objectType.apiName}. Valid names are: ${allPropertyApiNames.toString()}`);
        }
    }

}

And then you could call it just before doing the filtering:

function getAttribute(
  desiredAttr: string,
  desiredValue: string,
): Promise<DesiredObjectType> {
  Utils.checkPropertyApiNameIsValid(desiredAttr, DesiredObjectType);
  const desiredObjects = Objects.search().DesiredObjects().filter(obj => (obj as any)[desiredAttr].exactMatch(desiredValue));
  return desiredObjects;
}
1 Like