Skip to content

Instantly share code, notes, and snippets.

@letswritetw
Last active August 18, 2023 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save letswritetw/260dfd44ca3a64523d633642ffe60cd5 to your computer and use it in GitHub Desktop.
Save letswritetw/260dfd44ca3a64523d633642ffe60cd5 to your computer and use it in GitHub Desktop.
gas-import-postman-collections
const postmanApiKey = '請貼上 Postman API Key';
const githubToken = '請貼上 GitHub Access Token';
const repoOwner = '請貼上 GitHub 帳號名稱';
// 以下請貼上要匯進 Postman Collection 的清單
const repoList = [
{
repoName: 'postman-backup-demo',
filePath: 'Postman Collections/postman-backup-demo.json'
}
]
// 取 GitHub 備份檔
function getGitHubBackupFile({ repoName, filePath }) {
const apiUrl = `https://api.github.com/repos/${repoOwner}/${repoName}/contents/${filePath}`;
const headers = {
'Authorization': 'token ' + githubToken,
'Accept': 'application/vnd.github.v3.raw'
};
const response = UrlFetchApp.fetch(apiUrl, { headers });
const content = response.getContentText();
// Postman 匯入 GitHub 備份檔
importCollection(content)
}
// Postman 匯入 GitHub 備份檔
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);
const jsonResponse = response.getContentText();
}
// 檢查是否有同名的 Collection
function getExistingCollectionId(collectionName, apiKey) {
const apiUrl = 'https://api.getpostman.com/collections';
const headers = { 'X-Api-Key': apiKey };
const response = UrlFetchApp.fetch(apiUrl, { headers: 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