2021-11-04 09:00:09 +00:00
|
|
|
import { Storage } from '@google-cloud/storage';
|
2022-03-10 06:59:48 +00:00
|
|
|
import { ConnectionTestResult, QueryError, QueryResult, QueryService } from '@tooljet-plugins/common';
|
2022-01-17 07:08:17 +00:00
|
|
|
import { listBuckets, signedUrlForGet, signedUrlForPut, listFiles, getFile, uploadFile } from './operations';
|
2022-03-10 06:59:48 +00:00
|
|
|
import { SourceOptions, QueryOptions } from './types';
|
2022-01-17 07:08:17 +00:00
|
|
|
|
2021-11-04 09:00:09 +00:00
|
|
|
export default class GcsQueryService implements QueryService {
|
2022-01-24 13:59:21 +00:00
|
|
|
async run(sourceOptions: SourceOptions, queryOptions: QueryOptions): Promise<QueryResult> {
|
2021-11-04 09:00:09 +00:00
|
|
|
const operation = queryOptions.operation;
|
|
|
|
|
const client = await this.getConnection(sourceOptions);
|
|
|
|
|
let result = {};
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
switch (operation) {
|
|
|
|
|
case 'list_buckets':
|
|
|
|
|
result = await listBuckets(client, {});
|
|
|
|
|
break;
|
|
|
|
|
case 'list_files':
|
|
|
|
|
result = await listFiles(client, queryOptions);
|
|
|
|
|
break;
|
|
|
|
|
case 'get_file':
|
|
|
|
|
result = await getFile(client, queryOptions);
|
|
|
|
|
break;
|
|
|
|
|
case 'upload_file':
|
|
|
|
|
result = await uploadFile(client, queryOptions);
|
|
|
|
|
break;
|
|
|
|
|
case 'signed_url_for_get':
|
|
|
|
|
result = await signedUrlForGet(client, queryOptions);
|
|
|
|
|
break;
|
|
|
|
|
case 'signed_url_for_put':
|
|
|
|
|
result = await signedUrlForPut(client, queryOptions);
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
} catch (error) {
|
|
|
|
|
throw new QueryError('Query could not be completed', error.message, {});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
status: 'ok',
|
|
|
|
|
data: result,
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
2022-01-24 13:59:21 +00:00
|
|
|
async testConnection(sourceOptions: SourceOptions): Promise<ConnectionTestResult> {
|
2021-11-04 09:00:09 +00:00
|
|
|
const client: Storage = await this.getConnection(sourceOptions);
|
|
|
|
|
await listBuckets(client, {});
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
status: 'ok',
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
2022-01-24 13:59:21 +00:00
|
|
|
async getConnection(sourceOptions: SourceOptions): Promise<any> {
|
2021-11-04 09:00:09 +00:00
|
|
|
const privateKey = JSON.parse(sourceOptions['private_key']);
|
|
|
|
|
const storage = new Storage({
|
|
|
|
|
projectId: privateKey['project_id'],
|
|
|
|
|
credentials: {
|
|
|
|
|
client_email: privateKey['client_email'],
|
|
|
|
|
private_key: privateKey['private_key'],
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return storage;
|
|
|
|
|
}
|
2022-03-10 06:59:48 +00:00
|
|
|
}
|