import { resolveMicrosoftIntegration } from './accounts.ts'
import { graphRequest, isReadOnlyMethod, type GraphRequestParams } from './core.ts'
import { type GraphMethod } from './scopes.ts'
import { inputRecord, optionalRecord, optionalString, requiredString } from './validation.ts'
function parseMethod(value: string | undefined): GraphMethod {
const method = (value ?? 'GET').toUpperCase()
switch (method) {
case 'GET':
case 'POST':
case 'PATCH':
case 'PUT':
case 'DELETE':
return method
default:
throw new Error('method must be GET, POST, PATCH, PUT, or DELETE.')
}
}
/**
* Call any Microsoft Graph v1.0 path through the saved microsoft OAuth integration.
* Mutating requests require `confirm: true`; use `dryRun: true` to preview.
* @example
* import request from 'kody:@kody/microsoft/request'
* const me = await request({ path: '/me', query: { $select: 'id,displayName' } })
*/
export default async function request(params: Record<string, unknown> = {}) {
const input = inputRecord(params)
const path = requiredString(input, 'path')
const method = parseMethod(optionalString(input, 'method'))
const body = optionalRecord(input, 'body')
const query = optionalRecord(input, 'query') as GraphRequestParams['query']
const integration = optionalString(input, 'integration')
const account = optionalString(input, 'account')
if (!isReadOnlyMethod(method)) {
if (input.dryRun === true) {
return {
dryRun: true as const,
method,
path,
query: query ?? null,
body: body ?? null,
integration: resolveMicrosoftIntegration({ integration, account }),
}
}
if (input.confirm !== true) {
throw new Error(
method +
' ' +
path +
' mutates Microsoft 365 data and requires confirm: true after explicit user approval. Use dryRun: true to preview.',
)
}
}
return graphRequest({
integration: resolveMicrosoftIntegration({ integration, account }),
path,
method,
query,
body,
})
}