I have a structured data model that I have built on one site and I want to be able to use in in another space. How can I export / import the definition of this structured data model from one space to another?
Hi @jhs129,
You can use content API to import and write API to upload. You can also use the download JSON option Download/uploading content
Hi @garima I see how you can do that for page content in the page editor but what about for structured data?
Hello @jhs129,
I apologize for the earlier provided script example, which appears to be non-functional. You can utilize the builder Admin API to retrieve all the structured data models from one space and subsequently import those models into another space.
Here’s a verified script example that demonstrates the import and export of data models from one organization to another:
const { createAdminApiClient } = require("@builder.io/admin-sdk");
// Admin SDK for the source space
const adminSDKSource = createAdminApiClient("source-space-private-api-key");
// Admin SDK for the target space
const adminSDKTarget = createAdminApiClient("target-space-private-api-key");
// Function to get data models from the source space
async function getDataModels() {
const models = await adminSDKSource.query({
models: {
name: true,
id: true,
fields: true,
kind: true,
},
}).then((res) => res.data.models);
return models.filter(model => model.kind === 'data');
}
// Function to recursively map fields, including subfields if present
function mapFields(fields) {
return fields.map(field => {
const mappedField = {
type: field.type,
"@type": "@builder.io/core:Field",
required: field.required,
hideFromFieldsEditor: field.hideFromFieldsEditor,
name: field.name,
helperText: field.helperText,
};
if (field.subFields && Array.isArray(field.subFields)) {
mappedField.subFields = mapFields(field.subFields);
}
return mappedField;
});
}
// Function to add data models to the target space
async function addDataModelToTarget(targetModel) {
try {
const response = await adminSDKTarget.chain.mutation.addModel({
body: {
designerVersion: 1,
name: targetModel.name,
kind: "data",
ownerId: "Target Space public API Key", // You might want to replace this with the correct ownerId for the target space
examplePageUrl: "http://localhost:3000/",
helperText: targetModel.helperText || "Data model added from source space",
pathPrefix: "/",
fields: mapFields(targetModel.fields), // Use the recursive mapping function here
// Add other relevant fields if needed
},
}).execute({
id: true,
name: true,
kind: true,
});
console.log("Create model", response);
} catch (error) {
console.error("Error creating model:", error);
}
}
(async () => {
const dataModels = await getDataModels();
for (const model of dataModels) {
console.log("Processing model:", model.name);
await addDataModelToTarget(model);
}
console.log("Finished processing all data models.");
})();
To know more, you can visit the below links