Twenty sdk cli oauth (#18638)
<img width="1418" height="804" alt="image" src="https://github.com/user-attachments/assets/de6c8222-6496-4a71-bc21-7e5e1269d5cb" /> --------- Co-authored-by: Félix Malfait <felix.malfait@gmail.com> Co-authored-by: Félix Malfait <felix@twenty.com>
This commit is contained in:
@@ -0,0 +1,177 @@
|
||||
import { ConfigService } from '@/cli/utilities/config/config-service';
|
||||
import axios, { type AxiosInstance } from 'axios';
|
||||
import chalk from 'chalk';
|
||||
|
||||
export class ApiClient {
|
||||
readonly client: AxiosInstance;
|
||||
readonly configService: ConfigService;
|
||||
private readonly tokenOverride?: string;
|
||||
readonly serverUrlOverride?: string;
|
||||
|
||||
constructor(options?: {
|
||||
disableInterceptors?: boolean;
|
||||
serverUrl?: string;
|
||||
token?: string;
|
||||
}) {
|
||||
const { disableInterceptors = false, serverUrl, token } = options || {};
|
||||
this.configService = new ConfigService();
|
||||
this.tokenOverride = token;
|
||||
this.serverUrlOverride = serverUrl;
|
||||
this.client = axios.create();
|
||||
|
||||
this.client.interceptors.request.use(async (config) => {
|
||||
const twentyConfig = await this.configService.getConfig();
|
||||
|
||||
config.baseURL = this.serverUrlOverride ?? twentyConfig.apiUrl;
|
||||
|
||||
if (!config.headers.Authorization) {
|
||||
const authToken = await this.resolveAuthToken();
|
||||
|
||||
if (authToken) {
|
||||
config.headers.Authorization = `Bearer ${authToken}`;
|
||||
}
|
||||
}
|
||||
|
||||
return config;
|
||||
});
|
||||
|
||||
if (disableInterceptors) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.client.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error) => {
|
||||
if (error.response?.status === 401) {
|
||||
console.error(
|
||||
chalk.red(
|
||||
'Authentication failed. Run `twenty remote add` to authenticate.',
|
||||
),
|
||||
);
|
||||
} else if (error.response?.status === 403) {
|
||||
console.error(
|
||||
chalk.red(
|
||||
'Access denied. Check your API key and workspace permissions.',
|
||||
),
|
||||
);
|
||||
} else if (error.code === 'ECONNREFUSED') {
|
||||
console.error(
|
||||
chalk.red('Cannot connect to Twenty server. Is it running?'),
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async validateAuth(): Promise<{ authValid: boolean; serverUp: boolean }> {
|
||||
try {
|
||||
const query = `
|
||||
query CurrentWorkspace {
|
||||
currentWorkspace {
|
||||
id
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await this.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
authValid: response.status === 200 && !response.data.errors,
|
||||
serverUp: response.status === 200,
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
return {
|
||||
authValid: false,
|
||||
serverUp: true,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
authValid: false,
|
||||
serverUp: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async refreshToken(): Promise<string | null> {
|
||||
const config = await this.configService.getConfig();
|
||||
|
||||
if (!config.refreshToken || !config.oauthClientId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const tokenResponse = await axios.post(`${config.apiUrl}/oauth/token`, {
|
||||
grant_type: 'refresh_token',
|
||||
refresh_token: config.refreshToken,
|
||||
client_id: config.oauthClientId,
|
||||
});
|
||||
|
||||
const { access_token: newAccessToken, refresh_token: newRefreshToken } =
|
||||
tokenResponse.data;
|
||||
|
||||
await this.configService.setConfig({
|
||||
accessToken: newAccessToken,
|
||||
...(newRefreshToken ? { refreshToken: newRefreshToken } : {}),
|
||||
});
|
||||
|
||||
return newAccessToken;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async resolveAuthToken(): Promise<string | undefined> {
|
||||
if (this.tokenOverride) {
|
||||
return this.tokenOverride;
|
||||
}
|
||||
|
||||
const envToken = process.env.TWENTY_TOKEN;
|
||||
|
||||
if (envToken) {
|
||||
return envToken;
|
||||
}
|
||||
|
||||
const config = await this.configService.getConfig();
|
||||
const accessToken = config.accessToken;
|
||||
|
||||
if (accessToken && this.isTokenExpired(accessToken)) {
|
||||
const refreshed = await this.refreshToken();
|
||||
|
||||
if (refreshed) {
|
||||
return refreshed;
|
||||
}
|
||||
}
|
||||
|
||||
return accessToken ?? config.apiKey;
|
||||
}
|
||||
|
||||
private isTokenExpired(token: string): boolean {
|
||||
try {
|
||||
const payload = JSON.parse(
|
||||
Buffer.from(token.split('.')[1], 'base64').toString(),
|
||||
);
|
||||
|
||||
const EXPIRATION_MARGIN_IN_SECONDS = 30;
|
||||
|
||||
return (
|
||||
payload.exp * 1_000 < Date.now() + EXPIRATION_MARGIN_IN_SECONDS * 1_000
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,286 @@
|
||||
import { type ApiResponse } from '@/cli/utilities/api/api-response-type';
|
||||
import axios, { type AxiosInstance, type AxiosResponse } from 'axios';
|
||||
import { type Manifest } from 'twenty-shared/application';
|
||||
|
||||
export class ApplicationApi {
|
||||
constructor(private readonly client: AxiosInstance) {}
|
||||
|
||||
async findApplicationRegistrationByUniversalIdentifier(
|
||||
universalIdentifier: string,
|
||||
): Promise<
|
||||
ApiResponse<{
|
||||
id: string;
|
||||
universalIdentifier: string;
|
||||
name: string;
|
||||
oAuthClientId: string;
|
||||
} | null>
|
||||
> {
|
||||
try {
|
||||
const query = `
|
||||
query FindApplicationRegistrationByUniversalIdentifier($universalIdentifier: String!) {
|
||||
findApplicationRegistrationByUniversalIdentifier(universalIdentifier: $universalIdentifier) {
|
||||
id
|
||||
universalIdentifier
|
||||
name
|
||||
oAuthClientId
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await this.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query,
|
||||
variables: { universalIdentifier },
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error: response.data.errors[0],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data
|
||||
.findApplicationRegistrationByUniversalIdentifier,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async createApplicationRegistration(input: {
|
||||
name: string;
|
||||
description?: string;
|
||||
universalIdentifier: string;
|
||||
}): Promise<
|
||||
ApiResponse<{
|
||||
applicationRegistration: {
|
||||
id: string;
|
||||
universalIdentifier: string;
|
||||
oAuthClientId: string;
|
||||
};
|
||||
clientSecret: string;
|
||||
}>
|
||||
> {
|
||||
try {
|
||||
const mutation = `
|
||||
mutation CreateApplicationRegistration($input: CreateApplicationRegistrationInput!) {
|
||||
createApplicationRegistration(input: $input) {
|
||||
applicationRegistration {
|
||||
id
|
||||
universalIdentifier
|
||||
oAuthClientId
|
||||
}
|
||||
clientSecret
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await this.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query: mutation,
|
||||
variables: { input },
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error: response.data.errors[0],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.createApplicationRegistration,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async createDevelopmentApplication(input: {
|
||||
universalIdentifier: string;
|
||||
name: string;
|
||||
}): Promise<ApiResponse<{ id: string; universalIdentifier: string }>> {
|
||||
try {
|
||||
const mutation = `
|
||||
mutation CreateDevelopmentApplication($universalIdentifier: String!, $name: String!) {
|
||||
createDevelopmentApplication(universalIdentifier: $universalIdentifier, name: $name) {
|
||||
id
|
||||
universalIdentifier
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await this.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query: mutation,
|
||||
variables: input,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error: response.data.errors[0],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.createDevelopmentApplication,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async syncApplication(manifest: Manifest): Promise<ApiResponse> {
|
||||
try {
|
||||
const mutation = `
|
||||
mutation SyncApplication($manifest: JSON!) {
|
||||
syncApplication(manifest: $manifest) {
|
||||
applicationUniversalIdentifier
|
||||
actions
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const variables = { manifest };
|
||||
|
||||
const response: AxiosResponse = await this.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query: mutation,
|
||||
variables,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error: response.data.errors[0],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.syncApplication,
|
||||
message: `Successfully synced application: ${manifest.application.displayName}`,
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
const graphqlErrors = error.response.data?.errors;
|
||||
|
||||
if (Array.isArray(graphqlErrors) && graphqlErrors.length > 0) {
|
||||
return {
|
||||
success: false,
|
||||
error: graphqlErrors[0]?.message || error.message,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
error.response.data?.message ||
|
||||
`HTTP ${error.response.status}: ${error.message}`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async uninstallApplication(
|
||||
universalIdentifier: string,
|
||||
): Promise<ApiResponse> {
|
||||
try {
|
||||
const mutation = `
|
||||
mutation UninstallApplication($universalIdentifier: String!) {
|
||||
uninstallApplication(universalIdentifier: $universalIdentifier)
|
||||
}
|
||||
`;
|
||||
|
||||
const variables = { universalIdentifier };
|
||||
|
||||
const response: AxiosResponse = await this.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query: mutation,
|
||||
variables,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
response.data.errors[0]?.message || 'Failed to delete application',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.uninstallApplication,
|
||||
message: 'Successfully uninstalled application',
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.response.data?.errors?.[0]?.message || error.message,
|
||||
};
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,277 @@
|
||||
import { type ApiResponse } from '@/cli/utilities/api/api-response-type';
|
||||
import axios, { type AxiosInstance, type AxiosResponse } from 'axios';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { type FileFolder } from 'twenty-shared/types';
|
||||
import { pascalCase } from 'twenty-shared/utils';
|
||||
|
||||
const MIME_TYPES: Record<string, string> = {
|
||||
'.jpg': 'image/jpeg',
|
||||
'.jpeg': 'image/jpeg',
|
||||
'.png': 'image/png',
|
||||
'.gif': 'image/gif',
|
||||
'.webp': 'image/webp',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.bmp': 'image/bmp',
|
||||
'.ico': 'image/x-icon',
|
||||
'.pdf': 'application/pdf',
|
||||
'.doc': 'application/msword',
|
||||
'.docx':
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'.xls': 'application/vnd.ms-excel',
|
||||
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'.ppt': 'application/vnd.ms-powerpoint',
|
||||
'.pptx':
|
||||
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
'.txt': 'text/plain',
|
||||
'.csv': 'text/csv',
|
||||
'.json': 'application/json',
|
||||
'.xml': 'application/xml',
|
||||
'.zip': 'application/zip',
|
||||
'.tar': 'application/x-tar',
|
||||
'.gz': 'application/gzip',
|
||||
'.mp3': 'audio/mpeg',
|
||||
'.mp4': 'video/mp4',
|
||||
'.avi': 'video/x-msvideo',
|
||||
'.mov': 'video/quicktime',
|
||||
'.js': 'application/javascript',
|
||||
'.ts': 'application/typescript',
|
||||
'.jsx': 'application/javascript',
|
||||
'.tsx': 'application/typescript',
|
||||
'.html': 'text/html',
|
||||
'.css': 'text/css',
|
||||
};
|
||||
|
||||
const getMimeType = (filename: string): string => {
|
||||
const ext = path.extname(filename).toLowerCase();
|
||||
|
||||
return MIME_TYPES[ext] || 'application/octet-stream';
|
||||
};
|
||||
|
||||
export class FileApi {
|
||||
constructor(private readonly client: AxiosInstance) {}
|
||||
|
||||
// TODO: Migrate to MetadataClient once available
|
||||
// (see https://github.com/twentyhq/core-team-issues/issues/2289)
|
||||
async uploadAppTarball({
|
||||
tarballBuffer,
|
||||
universalIdentifier,
|
||||
}: {
|
||||
tarballBuffer: Buffer;
|
||||
universalIdentifier?: string;
|
||||
}): Promise<
|
||||
ApiResponse<{
|
||||
id: string;
|
||||
universalIdentifier: string;
|
||||
name: string;
|
||||
}>
|
||||
> {
|
||||
try {
|
||||
const mutation = `
|
||||
mutation UploadAppTarball($file: Upload!, $universalIdentifier: String) {
|
||||
uploadAppTarball(file: $file, universalIdentifier: $universalIdentifier) {
|
||||
id
|
||||
universalIdentifier
|
||||
name
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const operations = JSON.stringify({
|
||||
query: mutation,
|
||||
variables: {
|
||||
file: null,
|
||||
universalIdentifier: universalIdentifier ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
const map = JSON.stringify({
|
||||
'0': ['variables.file'],
|
||||
});
|
||||
|
||||
const formData = new FormData();
|
||||
|
||||
formData.append('operations', operations);
|
||||
formData.append('map', map);
|
||||
formData.append(
|
||||
'0',
|
||||
new Blob([new Uint8Array(tarballBuffer)], {
|
||||
type: 'application/gzip',
|
||||
}),
|
||||
'app.tar.gz',
|
||||
);
|
||||
|
||||
const response: AxiosResponse = await this.client.post(
|
||||
'/metadata',
|
||||
formData,
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error: response.data.errors[0]?.message || 'Failed to upload tarball',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.uploadAppTarball,
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.response.data?.errors?.[0]?.message || error.message,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async installTarballApp({
|
||||
universalIdentifier,
|
||||
}: {
|
||||
universalIdentifier: string;
|
||||
}): Promise<ApiResponse<boolean>> {
|
||||
try {
|
||||
const mutation = `
|
||||
mutation InstallMarketplaceApp($universalIdentifier: String!) {
|
||||
installMarketplaceApp(universalIdentifier: $universalIdentifier)
|
||||
}
|
||||
`;
|
||||
|
||||
const response: AxiosResponse = await this.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query: mutation,
|
||||
variables: { universalIdentifier },
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
response.data.errors[0]?.message || 'Failed to install application',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.installMarketplaceApp,
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.response.data?.errors?.[0]?.message || error.message,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async uploadFile({
|
||||
filePath,
|
||||
builtHandlerPath,
|
||||
fileFolder,
|
||||
applicationUniversalIdentifier,
|
||||
}: {
|
||||
filePath: string;
|
||||
builtHandlerPath: string;
|
||||
fileFolder: FileFolder;
|
||||
applicationUniversalIdentifier: string;
|
||||
}): Promise<ApiResponse<boolean>> {
|
||||
try {
|
||||
const absolutePath = path.resolve(filePath);
|
||||
|
||||
if (!fs.existsSync(absolutePath)) {
|
||||
return {
|
||||
success: false,
|
||||
error: `File not found: ${absolutePath}`,
|
||||
};
|
||||
}
|
||||
|
||||
const filename = path.basename(absolutePath);
|
||||
const buffer = fs.readFileSync(absolutePath);
|
||||
const mimeType = getMimeType(filename);
|
||||
|
||||
const mutation = `
|
||||
mutation UploadApplicationFile($file: Upload!, $applicationUniversalIdentifier: String!, $fileFolder: FileFolder!, $filePath: String!) {
|
||||
uploadApplicationFile(file: $file, applicationUniversalIdentifier: $applicationUniversalIdentifier, fileFolder: $fileFolder, filePath: $filePath)
|
||||
{ path }
|
||||
}
|
||||
`;
|
||||
|
||||
const graphqlEnumFileFolder = pascalCase(fileFolder);
|
||||
|
||||
const operations = JSON.stringify({
|
||||
query: mutation,
|
||||
variables: {
|
||||
file: null,
|
||||
applicationUniversalIdentifier,
|
||||
filePath: builtHandlerPath,
|
||||
fileFolder: graphqlEnumFileFolder,
|
||||
},
|
||||
});
|
||||
|
||||
const map = JSON.stringify({
|
||||
'0': ['variables.file'],
|
||||
});
|
||||
|
||||
const formData = new FormData();
|
||||
|
||||
formData.append('operations', operations);
|
||||
formData.append('map', map);
|
||||
formData.append(
|
||||
'0',
|
||||
new Blob([new Uint8Array(buffer)], { type: mimeType }),
|
||||
filename,
|
||||
);
|
||||
|
||||
const response: AxiosResponse = await this.client.post(
|
||||
'/metadata',
|
||||
formData,
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error: response.data.errors[0]?.message || 'Failed to upload file',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.uploadApplicationFile,
|
||||
message: `Successfully uploaded ${filename}`,
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
return {
|
||||
success: false,
|
||||
error: error.response.data?.errors?.[0]?.message || error.message,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
import { type ApiClient } from '@/cli/utilities/api/api-client';
|
||||
import { type ApiResponse } from '@/cli/utilities/api/api-response-type';
|
||||
import { createClient } from 'graphql-sse';
|
||||
|
||||
export class LogicFunctionApi {
|
||||
constructor(private readonly apiClient: ApiClient) {}
|
||||
|
||||
async findLogicFunctions(): Promise<
|
||||
ApiResponse<
|
||||
Array<{
|
||||
id: string;
|
||||
name: string;
|
||||
universalIdentifier: string;
|
||||
applicationId: string | null;
|
||||
}>
|
||||
>
|
||||
> {
|
||||
try {
|
||||
const query = `
|
||||
query FindManyLogicFunctions {
|
||||
findManyLogicFunctions {
|
||||
id
|
||||
name
|
||||
universalIdentifier
|
||||
applicationId
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const response = await this.apiClient.client.post(
|
||||
'/metadata',
|
||||
{ query },
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
response.data.errors[0]?.message || 'Failed to fetch functions',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.findManyLogicFunctions,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async executeLogicFunction({
|
||||
functionId,
|
||||
payload,
|
||||
}: {
|
||||
functionId: string;
|
||||
payload: Record<string, unknown>;
|
||||
}): Promise<
|
||||
ApiResponse<{
|
||||
data: unknown;
|
||||
logs: string;
|
||||
duration: number;
|
||||
status: string;
|
||||
error?: {
|
||||
errorType: string;
|
||||
errorMessage: string;
|
||||
stackTrace: string;
|
||||
};
|
||||
}>
|
||||
> {
|
||||
try {
|
||||
const mutation = `
|
||||
mutation ExecuteOneLogicFunction($input: ExecuteOneLogicFunctionInput!) {
|
||||
executeOneLogicFunction(input: $input) {
|
||||
data
|
||||
logs
|
||||
duration
|
||||
status
|
||||
error
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const variables = {
|
||||
input: {
|
||||
id: functionId,
|
||||
payload,
|
||||
},
|
||||
};
|
||||
|
||||
const response = await this.apiClient.client.post(
|
||||
'/metadata',
|
||||
{
|
||||
query: mutation,
|
||||
variables,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
response.data.errors[0]?.message ||
|
||||
'Failed to execute logic function',
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: response.data.data.executeOneLogicFunction,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async subscribeToLogs({
|
||||
applicationUniversalIdentifier,
|
||||
functionUniversalIdentifier,
|
||||
functionName,
|
||||
}: {
|
||||
applicationUniversalIdentifier: string;
|
||||
functionUniversalIdentifier?: string;
|
||||
functionName?: string;
|
||||
}) {
|
||||
const twentyConfig = await this.apiClient.configService.getConfig();
|
||||
const baseUrl = this.apiClient.serverUrlOverride ?? twentyConfig.apiUrl;
|
||||
|
||||
const wsClient = createClient({
|
||||
url: baseUrl + '/metadata',
|
||||
headers: async () => {
|
||||
const authToken = await this.apiClient.resolveAuthToken();
|
||||
|
||||
return {
|
||||
Authorization: authToken ? `Bearer ${authToken}` : '',
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'text/event-stream',
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const query = `
|
||||
subscription SubscribeToLogs($input: LogicFunctionLogsInput!) {
|
||||
logicFunctionLogs(input: $input) {
|
||||
logs
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
const variables = {
|
||||
input: {
|
||||
applicationUniversalIdentifier,
|
||||
universalIdentifier: functionUniversalIdentifier,
|
||||
name: functionName,
|
||||
},
|
||||
};
|
||||
|
||||
wsClient.subscribe<{ logicFunctionLogs: { logs: string } }>(
|
||||
{
|
||||
query,
|
||||
variables,
|
||||
},
|
||||
{
|
||||
next: ({ data }) => console.log(data?.logicFunctionLogs.logs),
|
||||
error: (err: unknown) => console.error(err),
|
||||
complete: () => console.log('Completed'),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { type ApiResponse } from '@/cli/utilities/api/api-response-type';
|
||||
import axios, { type AxiosInstance } from 'axios';
|
||||
import { buildClientSchema, getIntrospectionQuery, printSchema } from 'graphql';
|
||||
|
||||
export class SchemaApi {
|
||||
constructor(private readonly client: AxiosInstance) {}
|
||||
|
||||
async getSchema(options?: {
|
||||
authToken?: string;
|
||||
}): Promise<ApiResponse<string>> {
|
||||
return this.introspectEndpoint('/graphql', options);
|
||||
}
|
||||
|
||||
async getMetadataSchema(options?: {
|
||||
authToken?: string;
|
||||
}): Promise<ApiResponse<string>> {
|
||||
return this.introspectEndpoint('/metadata', options);
|
||||
}
|
||||
|
||||
private async introspectEndpoint(
|
||||
endpoint: string,
|
||||
options?: { authToken?: string },
|
||||
): Promise<ApiResponse<string>> {
|
||||
try {
|
||||
const introspectionQuery = getIntrospectionQuery();
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: '*/*',
|
||||
};
|
||||
|
||||
if (options?.authToken) {
|
||||
headers.Authorization = `Bearer ${options.authToken}`;
|
||||
}
|
||||
|
||||
const response = await this.client.post(
|
||||
endpoint,
|
||||
{
|
||||
query: introspectionQuery,
|
||||
},
|
||||
{ headers },
|
||||
);
|
||||
|
||||
if (response.data.errors) {
|
||||
return {
|
||||
success: false,
|
||||
error: `GraphQL introspection errors: ${JSON.stringify(response.data.errors)}`,
|
||||
};
|
||||
}
|
||||
|
||||
const schema = buildClientSchema(response.data.data);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: printSchema(schema),
|
||||
message: `Successfully loaded schema from ${endpoint}`,
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
return {
|
||||
success: false,
|
||||
error:
|
||||
error.response.data?.errors?.[0]?.message ||
|
||||
`Failed to load schema from ${endpoint}`,
|
||||
};
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user