Skip to content

Instantly share code, notes, and snippets.

@letswritetw
Last active August 18, 2023 14:17
Show Gist options
  • Save letswritetw/1b692e33aa3825055491f7e71c8a98e1 to your computer and use it in GitHub Desktop.
Save letswritetw/1b692e33aa3825055491f7e71c8a98e1 to your computer and use it in GitHub Desktop.
gas-import-postman-collections
const gitLabToken = '請貼上 GitHub Access Token';
const postmanApiKey = '請貼上 Postman API Key';
// 以下請貼上要匯進 Postman Collection 的清單
const repoList = [
{
projectId: '48419806',
filePath: 'Postman_Collections/postman-backup-demo.json'
}
];
// 排程:更新 Postman Collection
function runPostman() {
repoList.forEach(repo => getGitLabBackupFile({ projectId: repo.projectId, filePath: repo.filePath }))
}
// 取 GitLab 備份檔
// ?ref=main,ref 後面填的是主分支的名稱,如果主分支是用 master 的話請改為 master
function getGitLabBackupFile({ projectId, filePath }) {
const apiUrl = `https://gitlab.com/api/v4/projects/${projectId}/repository/files/${encodeURIComponent(filePath)}?ref=main`;
const options = {
method: 'get',
headers: { 'Authorization': 'Bearer ' + gitLabToken }
};
const response = UrlFetchApp.fetch(apiUrl, options);
const data = response.getContentText();
const fileContent = JSON.parse(data).content;
// 解 base64 值
const decodedBytes = Utilities.base64Decode(fileContent);
// 位元組陣列轉為字串
const decodedText = Utilities.newBlob(decodedBytes).getDataAsString();
importCollection(decodedText);
}
// Postman 匯入 GitLab 備份檔
function importCollection(content) {
let apiUrl = 'https://api.getpostman.com/collections';
const headers = {
'Content-Type': 'application/json',
'X-Api-Key': postmanApiKey
};
const payload = { 'collection': JSON.parse(content) };
const options = {
method: 'get',
headers
};
// 檢查是否有同名的 Collection
const collectionName = payload.collection.info.name;
const existingCollectionId = getExistingCollectionId(collectionName, postmanApiKey);
if (existingCollectionId) {
// 有同名,覆蓋
apiUrl = apiUrl + '/' + existingCollectionId;
options.method = 'put';
options.payload = JSON.stringify(payload);
} else {
// 無同名,代表 Collection 不存在,新增
options.method = 'post';
options.payload = JSON.stringify(payload);
}
const response = UrlFetchApp.fetch(apiUrl, options);
}
// 檢查是否有同名的 Collection GitLab
function getExistingCollectionId(collectionName, apiKey) {
const apiUrl = 'https://api.getpostman.com/collections';
const headers = { 'X-Api-Key': apiKey };
const response = UrlFetchApp.fetch(apiUrl, { headers });
const jsonResponse = JSON.parse(response.getContentText());
const collections = jsonResponse.collections;
for (let i = 0; i < collections.length; i++) {
if (collections[i].name === collectionName) {
return collections[i].uid;
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment