-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
55 lines (48 loc) · 1.43 KB
/
index.js
File metadata and controls
55 lines (48 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
'use strict'
const fp = require('fastify-plugin')
function fastifyOpenAI (fastify, options, next) {
const { name, ...opts } = options
if (!opts.apiKey) {
return next(new Error('You must provide a OpenAI API key'))
}
const OpenAI = require('openai')
const openai = new OpenAI(opts)
if (name) {
if (openai[name]) {
// prevent overriding of default openai properties
return next(
new Error(
`fastify-openai '${name}' is a reserved keyword`
)
)
}
if (!fastify.openai) {
// bootstrap the openai property if it doesn't exist
fastify.decorate('openai', Object.create(null))
} else if (Object.prototype.hasOwnProperty.call(fastify.openai, name)) {
// prevent overriding of existing openai named instances
return next(
new Error(
`OpenAI instance with name '${name}' has already been registered`
)
)
}
// assign the openai named instance
fastify.openai[name] = openai
} else {
if (fastify.openai) {
// prevent duplicate registration of fastify-openai
return next(new Error('fastify-openai has already been registered'))
} else {
// assign the default openai instance
fastify.decorate('openai', openai)
}
}
next()
}
module.exports = fp(fastifyOpenAI, {
fastify: '5.x',
name: 'fastify-openai'
})
module.exports.default = fastifyOpenAI
module.exports.fastifyOpenAI = fastifyOpenAI