Skip to content

Commit

Permalink
implement gitlab api
Browse files Browse the repository at this point in the history
  • Loading branch information
tatashidayat committed Jun 5, 2024
1 parent 50f7496 commit 98b36b2
Show file tree
Hide file tree
Showing 3 changed files with 187 additions and 30 deletions.
116 changes: 116 additions & 0 deletions src/ui/modules/gitlabRepository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { utf8ToBase64 } from "@src/utilities/base64";
import {
urlExportRequestBody,
urlExportSettings,
} from "@typings/urlExportData";

export class GitlabRepository {
baseUrl: string;
token: string;

constructor(props: { baseUrl: string; token: string }) {
this.baseUrl = props.baseUrl;
this.token = props.token;
}

async upload(
{ client_payload: clientPayload }: urlExportRequestBody,
{ reference: branch }: urlExportSettings,
responseHandler: {
onError: () => void;
onLoaded: (request: XMLHttpRequest) => void;
}
) {
const encodedContent = utf8ToBase64(clientPayload.tokens);
const encodedFilepath = encodeURIComponent(clientPayload.filename);

let isFileExist: boolean;
try {
isFileExist = await this._checkFile(encodedFilepath, branch);
} catch (error) {
if (error && error.request && error.code === 401) {
responseHandler.onLoaded(error.request);
}
return;
}

const uploadRequest = new XMLHttpRequest();
uploadRequest.onerror = (_err) => responseHandler.onError();
uploadRequest.onload = (event) =>
responseHandler.onLoaded(event.target as XMLHttpRequest);

this._uploadFile({
request: uploadRequest,
content: encodedContent,
commitMessage: clientPayload.commitMessage,
filepath: encodedFilepath,
branch: branch,
isFileExist: isFileExist,
});
}

private _checkFile(
encodedFilepath: string,
branch: string
): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
const request = new XMLHttpRequest();
request.open(
"GET",
`${this.baseUrl}/repository/files/${encodedFilepath}?ref=${branch}`
);
request.setRequestHeader("Authorization", `Bearer ${this.token}`);

request.onreadystatechange = (_ev: ProgressEvent) => {
if (request.readyState !== XMLHttpRequest.DONE) {
return;
}

const statusCode = request.status;
if (statusCode === 200) {
resolve(true);
return;
}

if (statusCode === 404) {
resolve(false);
return;
}

reject({
code: statusCode,
message: request.response,
request: request,
});
};

request.send();
});
}

private _uploadFile(args: {
request: XMLHttpRequest;
filepath: string;
content: string;
commitMessage: string;
branch: string;
isFileExist: boolean;
}) {
const { isFileExist, request, branch, content, commitMessage, filepath } = args;

const body = {
branch: branch,
content: content,
commit_message: commitMessage,
encoding: "base64",
};
const encodedFilepath = encodeURIComponent(filepath);

request.open(
isFileExist ? "PUT" : "POST",
`${this.baseUrl}/repository/files/${encodedFilepath}`
);
request.setRequestHeader("Authorization", `Bearer ${this.token}`);
request.send(JSON.stringify(body));
}
}
92 changes: 62 additions & 30 deletions src/ui/modules/urlExport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ import { commands } from '@config/commands'
import config from '@config/config'
import { PluginMessage } from '@typings/pluginEvent'
import { urlExportRequestBody, urlExportSettings } from '@typings/urlExportData'
import { GitlabRepository } from './gitlabRepository'

const responeHandler = (request: XMLHttpRequest): string => {
const responseHandler = (request: XMLHttpRequest): string => {
// 401
if (request.status === 401) {
return '🚨 401: Check your access token'
Expand Down Expand Up @@ -40,45 +41,63 @@ const addUrlExportRequestHeaders = (request: XMLHttpRequest, exportSettings: url
}
}

const addUrlExportRequestEvents = (request: XMLHttpRequest) => {
// on error
request.onerror = (event) => {
// @ts-ignore
parent.postMessage({
function requestErrorHandler() {
parent.postMessage(
{
pluginMessage: {
command: commands.closePlugin,
payload: {
notification: '🚨 An error occurred while sending the tokens: check your settings & your server.'
}
} as PluginMessage
}, '*')
}
// show message on successful push
request.onload = (progressEvent: ProgressEvent) => {
// @ts-ignore
parent.postMessage({
notification:
"🚨 An error occurred while sending the tokens: check your settings & your server.",
},
} as PluginMessage,
},
"*"
);
}

function requestLoadedHandler(request: XMLHttpRequest) {
// @ts-ignore
parent.postMessage(
{
pluginMessage: {
command: commands.closePlugin,
payload: {
notification: responeHandler(progressEvent.target as XMLHttpRequest)
}
} as PluginMessage
}, '*')
}
notification: responseHandler(request),
},
} as PluginMessage,
},
"*"
);
}

const addUrlExportRequestEvents = (request: XMLHttpRequest) => {
// on error
request.onerror = (_event) => {
requestErrorHandler();
};
// show message on successful push
request.onload = (progressEvent: ProgressEvent) => {
requestLoadedHandler(progressEvent.target as XMLHttpRequest);
};
}

const generateUrlExportRequestBody = (exportSettings: urlExportSettings, requestBody: urlExportRequestBody) => {
let body
if (exportSettings.authType === config.key.authType.gitlabToken) {
body = new FormData()
body.append('token', exportSettings.accessToken)
body.append('ref', exportSettings.reference)
body.append('variables[FIGMA_EVENT_TYPE]', requestBody.event_type)
body.append('variables[FIGMA_CLIENT_PAYLOAD_TOKENS]', requestBody.client_payload.tokens)
body.append('variables[FIGMA_CLIENT_PAYLOAD_FILENAME]', requestBody.client_payload.filename)
body.append('variables[FIGMA_CLIENT_PAYLOAD_COMMIT_MESSAGE]', requestBody.client_payload.commitMessage)
} else {
body = JSON.stringify(requestBody, null, 2)
switch (exportSettings.authType) {
case config.key.authType.gitlabToken:
body = new FormData()
body.append('token', exportSettings.accessToken)
body.append('ref', exportSettings.reference)
body.append('variables[FIGMA_EVENT_TYPE]', requestBody.event_type)
body.append('variables[FIGMA_CLIENT_PAYLOAD_TOKENS]', requestBody.client_payload.tokens)
body.append('variables[FIGMA_CLIENT_PAYLOAD_FILENAME]', requestBody.client_payload.filename)
body.append('variables[FIGMA_CLIENT_PAYLOAD_COMMIT_MESSAGE]', requestBody.client_payload.commitMessage)
break;

default:
body = JSON.stringify(requestBody, null, 2)
break;
}
return body
}
Expand All @@ -96,6 +115,19 @@ const urlExport = (parent, exportSettings: urlExportSettings, requestBody: urlEx
} as PluginMessage
}, '*')
}

if (exportSettings.authType === config.key.authType.gitlabCommit) {
const gitlabRepo = new GitlabRepository({
baseUrl: exportSettings.url,
token: exportSettings.accessToken,
});
gitlabRepo.upload(requestBody, exportSettings, {
onError: requestErrorHandler,
onLoaded: requestLoadedHandler,
});
return;
}

// init request
const request = new XMLHttpRequest()
// send to user defined url
Expand Down
9 changes: 9 additions & 0 deletions src/utilities/base64.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const utf8ToBase64 = (text: string): string => {
const utf8EncodedBytes = new TextEncoder().encode(text);
const binString = Array.from(utf8EncodedBytes, (byte) =>
String.fromCodePoint(byte)
).join("");
return Buffer.from(binString, "base64").toString("base64");
};

export { utf8ToBase64 };

0 comments on commit 98b36b2

Please sign in to comment.