Creating an Object in Foundry Functions

Currently having an issue with object creation in functions.

Here is my function code (using “test” instead of the name of my real object)

@Function()
public addTest(testId: string): Test {
    const newObject = Objects.create().test(testId)
    return newObject
}

The function at the moment does not work (or at least, no new permanent Object is created). I can’t find any documentation for Objects.create(), but it appears as a recommended method in my code editor.

I would love any help with fixing up my code to create new objects as well as links to documentation if I come across any other issues down the line.

Hey,

Few changes/notes:

  1. Any time you’re writing a TypeScript function that modifies the Ontology (i.e., create a new object, delete an existing object, modify even just one property of an existing object, create a new link, delete an existing link), you need to use the @OntologyEditFunction() decorator instead of the standard @Function() decorator. You typically also pair it with the @Edits() decorator, where you’ll pass in the API name(s) of the Object Type(s) that will get modified.
  2. All @OntologyEditFunction() functions have a return type of void, regardless of what logic you’re implementing. This also means you don’t need your return line at the end.
  3. Consider using the Uuid library to create a unique identifier instead of passing in a string parameter. This lets the function itself handle the primary key generation instead of having to configure it in the Action Type in OMA or via Workshop (if you’re going to gate this function’s use via a user-facing application).

All-in-all, a modified version of your function may look like this:

import { OntologyEditFunction, Edits } from "@foundry/functions-api";
import { Objects, Test } from "@foundry/ontology-api";
import { Uuid } from "@foundry/functions-utils";

export class MyFunctions {
    
    @Edits(Test)
    @OntologyEditFunction()
    public addTest(): void {
        // You could skip storing the value in a variable and pass it in directly to the last line
        const newId = Uuid.random();
        const newObject = Objects.create().test(newId);
    }
} 

Note that when you test this via the Functions helper tab at the bottom, it will only simulate the intended changes based on the logic, but it won’t actually create a new object. You’ll have to create a new Action Type in OMA that is backed by this function, and then execute that Action to actually instantiate a new object instance.

Hope this helps and happy holidays!

Sounds good, thanks!