我正在研究nodejs项目,在这里我需要进行几次ms图形api调用以获取一些数据。某些示例调用如下
https://graph.microsoft.com/v1.0/users/{userPrincipalName}/manager
https://graph.microsoft.com/beta/users/{userPrincipalName}/notebooks
https://graph.microsoft.com/v1.0/users/{userPrincipalName}/photo/
我的目标是每次都不使用请求模块来调用3个以上的api并分别获取数据。我想创建某种if帮助函数,以便在其中传递需要使用的URL和{userPrincipalName}
所以我创建了graphendpoints.js来存储所有的URL
module.exports = {
manager: 'https://graph.microsoft.com/v1.0/users/userPrincipalName/manager',
notebooks: 'https://graph.microsoft.com/beta/users/{userPrincipalName}/notebooks',
photo: 'https://graph.microsoft.com/v1.0/users/{userPrincipalName}/photo/'
};
这是我通过身份验证令牌和网址通过单个函数进行图形调用的方式。我没有每个单独的方法来执行对经理,笔记本或照片等的请求。
executeGraphApi: function (token, url) {
return new Promise(function (resolve, reject) {
let parsedBody = []
request.get({
url: url,
headers: {
authorization: 'Bearer ' + token
}
},
function (err, response, body) {
if (err) {
reject(err)
} else {
parsedBody.push(JSON.parse(body).displayName)
resolve(parsedBody)
}
})
});
}
helper函数runMSGraphApi(url)在executeGraphApi(token,url)上方调用
var graphcallrunner = require('../../app/msgraph/graphcallrunner');
runMSGraphApi: function (url) {
return new Promise(function (resolve,reject) {
msGraph.getAccessToken()
.then(function (token) {
graphcallrunner.executeGraphApi(token,url)
.then(function (results) {
resolve(results)
})
.catch(function (error) {
reject(error)
})
})
.catch(function (error) {
console.log(error);
reject(error)
})
})
}
其消费者如下所示。我需要确保任何想调用ms graph的人都可以使用runMSGraphApi()并传递正确的url。
var graphendpoints = require('../../../msgraph/graphendpoints.js');
graphapihelper.runMSGraphApi(graphendpoints.manager),
如果您在上面看到,我从graphendpoints.js中选择了经理api调用,并传入了该URL。这个网址实际上是 https://graph.microsoft.com/v1.0/users/ {userPrincipalName} /经理
其中未插入{userPrincipalName}。如何将{userPrincipalName}的值动态传递给executeGraphApi()中的最终URL结构。
https://graph.microsoft.com/v1.0/users/bob.bar@google.com/manager
答案 0 :(得分:0)
您可以使用正则表达式
const endpoints = {
manager: 'https://graph.microsoft.com/v1.0/users/userPrincipalName/manager',
notebooks: 'https://graph.microsoft.com/beta/users/{userPrincipalName}/notebooks',
photo: 'https://graph.microsoft.com/v1.0/users/{userPrincipalName}/photo/'
}
function parseUrl(url, params) {
let result = url
const regex = /(?<={)(.*)(?=})/
const match = url.match(regex)
if (match) {
const replace = match[0]
const value = params[replace]
const holeThing = /{(?<={)(.*)(?=})}/
if (value) {
result = result.replace(holeThing, value);
} else {
throw new Error('Please specify the value for parsing the URL')
}
}
return result
}
const url = parseUrl(endpoints.notebooks, {
userPrincipalName: 'woof'
})
console.log(url)