Skip to main content

Product Attributes

Overview

Manage product attributes.

Product attributes are predefined properties or features of a product that give it identifiable traits. They're often structured as key-value pairs and are central to product management and user experience.

They are used to define the different variants of a product

Check here to see more information on the ProductAttribute class: ProductAttribute

Create Attribute

  try {
const attribute = new ProductAttribute(
ID.unique(),
new Date().toISOString(),
new Date().toISOString(),
'Color',
["Red", "Green", "Blue"]
);

await database.createDocument(
"[DATABASE_ID]",
"[PRODUCT_ATTR_COLLECTION_ID]",
attribute.$id,
attribute.toMap()
);

console.log('Attr created:', attribute);
} catch (error) {
if (error instanceof AppwriteException) {
console.error(`Error creating attribute : ${error.message} - ${error.code}`);
// display error message to the user
} else {
console.error('Unknown error:', error);
// display error message to the user
}
}

List All Attributes

  try {
const res = await database.listDocuments(
"[DATABASE_ID]",
"[PRODUCT_ATTR_COLLECTION_ID]",
[Query.limit(100)]
);

const attributes = res.documents.map((doc) => ProductAttribute.fromMap(doc));

const total = res.total; // total number of attributes

console.log('Attributes fetched:', attributes);
} catch (error) {
if (error instanceof AppwriteException) {
console.error(`Error fetching attributes: ${error.message} - ${error.code}`);
// display error message to the user
} else {
console.error('Unknown error:', error);
// display error message to the user
}
}

Delete An Attribute

  try {
await database.deleteDocument(
"[DATABASE_ID]",
"[PRODUCT_ATTR_COLLECTION_ID]",
"[ATTRIBUTE_ID]"
);

console.log('Attr deleted successfully');
} catch (error) {
if (error instanceof AppwriteException) {
console.error(`Error deleting attribute: ${error.message} - ${error.code}`);
// display error message to the user
} else {
console.error('Unknown error:', error);
// display error message to the user
}
}

Edit/Update An Attribute

  try {
await database.updateDocument(
"[DATABASE_ID]",
"[PRODUCT_ATTR_COLLECTION_ID]",
"[ATTRIBUTE_ID]",
{
"name": "New Name",
"values": ["value1", "value2"]
}
);

console.log('Attr updated successfully');
} catch (error) {
if (error instanceof AppwriteException) {
console.error(`Error updating attribute: ${error.message} - ${error.code}`);
// display error message to the user
} else {
console.error('Unknown error:', error);
// display error message to the user
}
}