1
0
Fork 0
peertube/shared/core-utils/plugins/hooks.ts

62 lines
1.4 KiB
TypeScript
Raw Normal View History

import { RegisteredExternalAuthConfig } from '@shared/models'
2019-07-18 12:28:37 +00:00
import { HookType } from '../../models/plugins/hook-type.enum'
2021-07-26 13:04:37 +00:00
import { isCatchable, isPromise } from '../common/promises'
2019-07-18 12:28:37 +00:00
function getHookType (hookName: string) {
if (hookName.startsWith('filter:')) return HookType.FILTER
if (hookName.startsWith('action:')) return HookType.ACTION
return HookType.STATIC
}
2022-08-02 13:29:00 +00:00
async function internalRunHook <T> (options: {
handler: Function
hookType: HookType
result: T
params: any
onError: (err: Error) => void
}) {
const { handler, hookType, result, params, onError } = options
2019-07-18 12:28:37 +00:00
try {
2019-07-19 15:30:41 +00:00
if (hookType === HookType.FILTER) {
const p = handler(result, params)
2022-08-02 13:29:00 +00:00
const newResult = isPromise(p)
? await p
: p
2019-07-19 15:30:41 +00:00
2022-08-02 13:29:00 +00:00
return newResult
2019-07-19 15:30:41 +00:00
}
2019-07-18 12:28:37 +00:00
2019-07-19 15:30:41 +00:00
// Action/static hooks do not have result value
const p = handler(params)
if (hookType === HookType.STATIC) {
if (isPromise(p)) await p
return undefined
}
2019-07-18 12:28:37 +00:00
2019-07-19 15:30:41 +00:00
if (hookType === HookType.ACTION) {
2019-07-22 13:40:13 +00:00
if (isCatchable(p)) p.catch((err: any) => onError(err))
2019-07-18 12:28:37 +00:00
2019-07-19 15:30:41 +00:00
return undefined
2019-07-18 12:28:37 +00:00
}
} catch (err) {
onError(err)
}
return result
}
function getExternalAuthHref (apiUrl: string, auth: RegisteredExternalAuthConfig) {
return apiUrl + `/plugins/${auth.name}/${auth.version}/auth/${auth.authName}`
}
2019-07-18 12:28:37 +00:00
export {
getHookType,
internalRunHook,
getExternalAuthHref
2019-07-18 12:28:37 +00:00
}