Skip to content

Commit

Permalink
🐛 fix: fix PLUGINS_INDEX_URL not working (lobehub#793)
Browse files Browse the repository at this point in the history
  • Loading branch information
arvinxx committed Dec 24, 2023
1 parent 80c02ee commit 152913e
Show file tree
Hide file tree
Showing 9 changed files with 63 additions and 37 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { createGatewayOnEdgeRuntime } from '@lobehub/chat-plugins-gateway';

import { PLUGINS_INDEX_URL } from '@/const/url';
import { getServerConfig } from '@/config/server';

export const POST = createGatewayOnEdgeRuntime({ pluginsIndexUrl: PLUGINS_INDEX_URL });
const pluginsIndexUrl = getServerConfig().PLUGINS_INDEX_URL;

export const POST = createGatewayOnEdgeRuntime({ pluginsIndexUrl });
19 changes: 19 additions & 0 deletions src/app/api/plugin/store/Store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import urlJoin from 'url-join';

import { getServerConfig } from '@/config/server';
import { DEFAULT_LANG, checkLang } from '@/const/locale';
import { Locales } from '@/locales/resources';

export class PluginStore {
private readonly baseUrl: string;

constructor(baseUrl?: string) {
this.baseUrl = baseUrl || getServerConfig().PLUGINS_INDEX_URL;
}

getPluginIndexUrl = (lang: Locales = DEFAULT_LANG) => {
if (checkLang(lang)) return this.baseUrl;

return urlJoin(this.baseUrl, `index.${lang}.json`);
};
}
21 changes: 21 additions & 0 deletions src/app/api/plugin/store/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { DEFAULT_LANG } from '@/const/locale';

import { PluginStore } from './Store';

export const runtime = 'edge';

export const GET = async (req: Request) => {
const locale = new URL(req.url).searchParams.get('locale');

const pluginStore = new PluginStore();

let res: Response;

res = await fetch(pluginStore.getPluginIndexUrl(locale as any));

if (res.status === 404) {
res = await fetch(pluginStore.getPluginIndexUrl(DEFAULT_LANG));
}

return res;
};
9 changes: 0 additions & 9 deletions src/const/url.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import urlJoin from 'url-join';

import { Locales } from '@/locales/resources';

import pkg from '../../package.json';
import { DEFAULT_LANG, checkLang } from './locale';
import { INBOX_SESSION_ID } from './session';

export const GITHUB = pkg.homepage;
Expand All @@ -16,12 +13,6 @@ export const DISCORD = 'https://discord.gg/AYFPHvv2jT';

export const PLUGINS_INDEX_URL = 'https://chat-plugins.lobehub.com';

export const getPluginIndexJSON = (lang: Locales = DEFAULT_LANG, baseUrl = PLUGINS_INDEX_URL) => {
if (checkLang(lang)) return baseUrl;

return urlJoin(baseUrl, `index.${lang}.json`);
};

export const AGENTS_INDEX_GITHUB = 'https://github.com/lobehub/lobe-chat-agents';
export const AGENTS_INDEX_GITHUB_ISSUE = urlJoin(AGENTS_INDEX_GITHUB, 'issues/new');

Expand Down
13 changes: 3 additions & 10 deletions src/services/__tests__/plugin.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';
import { Mock, beforeEach, describe, expect, it, vi } from 'vitest';

import { getPluginIndexJSON } from '@/const/url';
import { PluginModel } from '@/database/models/plugin';
import { DB_Plugin } from '@/database/schemas/plugin';
import { globalHelpers } from '@/store/global/helpers';
Expand All @@ -13,9 +12,7 @@ import openAPIV3 from './openai/OpenAPI_V3.json';
import OpenAIPlugin from './openai/plugin.json';

// Mocking modules and functions
vi.mock('@/const/url', () => ({
getPluginIndexJSON: vi.fn(),
}));

vi.mock('@/store/global/helpers', () => ({
globalHelpers: {
getCurrentLanguage: vi.fn(),
Expand All @@ -40,9 +37,7 @@ describe('PluginService', () => {
it('should fetch and return the plugin list', async () => {
// Arrange
const fakeResponse = { plugins: [{ name: 'TestPlugin' }] };
const fakeUrl = 'http:https://fake-url.com/plugins.json';
(globalHelpers.getCurrentLanguage as Mock).mockReturnValue('en');
(getPluginIndexJSON as Mock).mockReturnValue(fakeUrl);
(globalHelpers.getCurrentLanguage as Mock).mockReturnValue('tt');
global.fetch = vi.fn(() =>
Promise.resolve({
json: () => Promise.resolve(fakeResponse),
Expand All @@ -54,16 +49,14 @@ describe('PluginService', () => {

// Assert
expect(globalHelpers.getCurrentLanguage).toHaveBeenCalled();
expect(getPluginIndexJSON).toHaveBeenCalledWith('en');
expect(fetch).toHaveBeenCalledWith(fakeUrl);
expect(fetch).toHaveBeenCalledWith('/api/plugin/store?locale=tt');
expect(pluginList).toEqual(fakeResponse);
});

it('should handle fetch error', async () => {
// Arrange
const fakeUrl = 'http:https://fake-url.com/plugins.json';
(globalHelpers.getCurrentLanguage as Mock).mockReturnValue('en');
(getPluginIndexJSON as Mock).mockReturnValue(fakeUrl);
global.fetch = vi.fn(() => Promise.reject(new Error('Network error')));

// Act & Assert
Expand Down
9 changes: 6 additions & 3 deletions src/services/_url.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
export const URLS = {
config: '/api/config',
market: '/api/market',
plugins: '/api/plugins',
proxy: '/api/proxy',
};

export const PLUGINS_URLS = {
gateway: '/api/plugin/gateway',
store: '/api/plugin/store',
};

export const OPENAI_URLS = {
Expand All @@ -16,5 +21,3 @@ export const TTS_URL = {
edge: '/api/tts/edge-speech',
microsoft: '/api/tts/microsoft-speech',
};

export const PROXY_URL = '/api/proxy';
4 changes: 2 additions & 2 deletions src/services/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { UserMessageContentPart } from '@/types/openai/chat';
import { fetchAIFactory, getMessageError } from '@/utils/fetch';

import { createHeaderWithOpenAI } from './_header';
import { OPENAI_URLS, URLS } from './_url';
import { OPENAI_URLS, PLUGINS_URLS } from './_url';

const isVisionModel = (model?: string) => model && VISION_MODEL_WHITE_LIST.includes(model);

Expand Down Expand Up @@ -92,7 +92,7 @@ class ChatService {

const gatewayURL = manifest?.gateway;

const res = await fetch(gatewayURL ?? URLS.plugins, {
const res = await fetch(gatewayURL ?? PLUGINS_URLS.gateway, {
body: JSON.stringify({ ...params, manifest }),
headers: createHeadersWithPluginSettings(settings),
method: 'POST',
Expand Down
4 changes: 2 additions & 2 deletions src/services/file.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { FileModel } from '@/database/models/file';
import { DB_File } from '@/database/schemas/files';
import { PROXY_URL } from '@/services/_url';
import { URLS } from '@/services/_url';
import { FilePreview } from '@/types/files';
import compressImage from '@/utils/compressImage';

Expand Down Expand Up @@ -43,7 +43,7 @@ class FileService {
}

async uploadImageByUrl(url: string, file: Pick<DB_File, 'name' | 'metadata'>) {
const res = await fetch(PROXY_URL, { body: url, method: 'POST' });
const res = await fetch(URLS.proxy, { body: url, method: 'POST' });
const data = await res.arrayBuffer();
const fileType = res.headers.get('content-type') || 'image/webp';

Expand Down
15 changes: 6 additions & 9 deletions src/services/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@ import {
pluginManifestSchema,
} from '@lobehub/chat-plugin-sdk';

import { getPluginIndexJSON } from '@/const/url';
import { PluginModel } from '@/database/models/plugin';
import { PROXY_URL } from '@/services/_url';
import { PLUGINS_URLS, URLS } from '@/services/_url';
import { globalHelpers } from '@/store/global/helpers';
import { OpenAIPluginManifest } from '@/types/openai/plugin';
import { LobeTool } from '@/types/tool';
Expand All @@ -22,7 +21,7 @@ class PluginService {
// 2. 发送请求
let res: Response;
try {
res = await (proxy ? fetch(PROXY_URL, { body: url, method: 'POST' }) : fetch(url));
res = await (proxy ? fetch(URLS.proxy, { body: url, method: 'POST' }) : fetch(url));
} catch {
throw new TypeError('fetchError');
}
Expand Down Expand Up @@ -52,14 +51,12 @@ class PluginService {
/**
* get plugin list from store
*/
getPluginList = async () => {
const url = getPluginIndexJSON(globalHelpers.getCurrentLanguage());
getPluginList = async (): Promise<LobeChatPluginsMarketIndex> => {
const locale = globalHelpers.getCurrentLanguage();

const res = await fetch(url);
const res = await fetch(`${PLUGINS_URLS.store}?locale=${locale}`);

const data: LobeChatPluginsMarketIndex = await res.json();

return data;
return res.json();
};

getPluginManifest = async (
Expand Down

0 comments on commit 152913e

Please sign in to comment.