SerpapiPlugin.tsx 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { useTranslation } from 'react-i18next'
  2. import Image from 'next/image'
  3. import SerpapiLogo from '../../assets/serpapi.png'
  4. import KeyValidator from '../key-validator'
  5. import type { Form, ValidateValue } from '../key-validator/declarations'
  6. import { updatePluginKey, validatePluginKey } from './utils'
  7. import { useToastContext } from '@/app/components/base/toast'
  8. import type { PluginProvider } from '@/models/common'
  9. type SerpapiPluginProps = {
  10. plugin: PluginProvider
  11. onUpdate: () => void
  12. }
  13. const SerpapiPlugin = ({
  14. plugin,
  15. onUpdate,
  16. }: SerpapiPluginProps) => {
  17. const { t } = useTranslation()
  18. const { notify } = useToastContext()
  19. const forms: Form[] = [{
  20. key: 'api_key',
  21. title: t('common.plugin.serpapi.apiKey'),
  22. placeholder: t('common.plugin.serpapi.apiKeyPlaceholder'),
  23. value: plugin.credentials?.api_key,
  24. validate: {
  25. before: (v) => {
  26. if (v?.api_key)
  27. return true
  28. },
  29. run: async (v) => {
  30. return validatePluginKey('serpapi', {
  31. credentials: {
  32. api_key: v?.api_key,
  33. },
  34. })
  35. },
  36. },
  37. handleFocus: (v, dispatch) => {
  38. if (v.api_key === plugin.credentials?.api_key)
  39. dispatch({ ...v, api_key: '' })
  40. },
  41. }]
  42. const handleSave = async (v: ValidateValue) => {
  43. if (!v?.api_key || v?.api_key === plugin.credentials?.api_key)
  44. return
  45. const res = await updatePluginKey('serpapi', {
  46. credentials: {
  47. api_key: v?.api_key,
  48. },
  49. })
  50. if (res.status === 'success') {
  51. notify({ type: 'success', message: t('common.actionMsg.modifiedSuccessfully') })
  52. onUpdate()
  53. return true
  54. }
  55. }
  56. return (
  57. <KeyValidator
  58. type='serpapi'
  59. title={<Image alt='serpapi logo' src={SerpapiLogo} width={64} />}
  60. status={plugin.credentials?.api_key ? 'success' : 'add'}
  61. forms={forms}
  62. keyFrom={{
  63. text: t('common.plugin.serpapi.keyFrom'),
  64. link: 'https://serpapi.com/manage-api-key',
  65. }}
  66. onSave={handleSave}
  67. />
  68. )
  69. }
  70. export default SerpapiPlugin