Skip to content

Commit c2fc99a

Browse files
Add snippet 'List Labels on a Drive Item' (#357)
1 parent 69f801b commit c2fc99a

File tree

1 file changed

+58
-2
lines changed

1 file changed

+58
-2
lines changed

advanced/driveLabels.gs

Lines changed: 58 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@ function listLabels() {
3333
} while (pageToken != null);
3434

3535
Logger.log('Found %d labels', labels.length);
36-
console.log(labels[0].name)
3736
}
3837
// [END apps_script_drive_labels_list_labels]
3938

@@ -50,4 +49,61 @@ function getLabel(labelName) {
5049
Logger.log('Failed to get label with error %s', err.message);
5150
}
5251
}
53-
// [END apps_script_drive_labels_get_label]
52+
// [END apps_script_drive_labels_get_label]
53+
54+
// [START apps_script_drive_labels_list_labels_on_drive_item]
55+
/*
56+
* List Labels on a Drive Item
57+
* Fetches a Drive Item and prints all applied values along with their to their human-readable names.
58+
*
59+
* - fileId: Drive File ID
60+
*/
61+
function listLabelsOnDriveItem(fileId) {
62+
try {
63+
const appliedLabels = Drive.Files.listLabels(fileId);
64+
65+
Logger.log("%d label(s) are applied to this file", appliedLabels.items.length);
66+
67+
appliedLabels.items.forEach((appliedLabel) => {
68+
// Resource name of the label at the applied revision.
69+
const labelName = "labels/" + appliedLabel.id + "@" + appliedLabel.revisionId;
70+
71+
Logger.log("Fetching Label: %s", labelName);
72+
const label = DriveLabels.Labels.get(labelName, {view: "LABEL_VIEW_FULL"});
73+
74+
Logger.log("Label Title: %s", label.properties.title);
75+
76+
Object.keys(appliedLabel.fields).forEach(fieldId => {
77+
const fieldValue = appliedLabel.fields[fieldId];
78+
const field = label.fields.find((f) => f.id == fieldId);
79+
80+
Logger.log("Field ID: %s, Display Name: %s", field.id, field.properties.displayName);
81+
switch(fieldValue.valueType) {
82+
case 'text':
83+
Logger.log("Text: %s", fieldValue.text[0]);
84+
break;
85+
case 'integer':
86+
Logger.log("Integer: %d", fieldValue.integer[0]);
87+
break;
88+
case 'dateString':
89+
Logger.log("Date: %s", fieldValue.dateString[0]);
90+
break;
91+
case 'user':
92+
Logger.log("User: %s", fieldValue.user.map((user) => user.emailAddress + ": " + user.displayName).join(", "));
93+
break;
94+
case 'selection':
95+
const choices = fieldValue.selection.map((choiceId) => field.selectionOptions.choices.find((choice) => choice.id == choiceId));
96+
Logger.log("Selection: %s", choices.map((choice) => choice.id + ": " + choice.properties.displayName).join(", "));
97+
break;
98+
default:
99+
Logger.log("Unknown: %s", fieldValue.valueType);
100+
Logger.log(fieldValue.value);
101+
}
102+
});
103+
});
104+
} catch (err) {
105+
// TODO (developer) - Handle exception
106+
Logger.log('Failed with error %s', err.message);
107+
}
108+
}
109+
// [END apps_script_drive_labels_list_labels_on_drive_item]

0 commit comments

Comments
 (0)