ToolJet/server/plugins/datasources/firestore/index.ts

96 lines
3 KiB
TypeScript
Raw Normal View History

import { Injectable } from '@nestjs/common';
2021-07-17 04:41:02 +00:00
import { parseJson } from 'src/helpers/utils.helper';
2021-07-18 07:20:46 +00:00
import { ConnectionTestResult } from 'src/modules/data_sources/connection_test_result.type';
2021-07-17 04:41:02 +00:00
import { QueryError } from 'src/modules/data_sources/query.error';
import { QueryResult } from 'src/modules/data_sources/query_result.type';
import { QueryService } from 'src/modules/data_sources/query_service.interface';
import {
addDocument,
bulkUpdate,
deleteDocument,
getDocument,
queryCollection,
setDocument,
updateDocument,
} from './operations';
const { Firestore } = require('@google-cloud/firestore');
@Injectable()
export default class FirestoreQueryService implements QueryService {
async run(sourceOptions: any, queryOptions: any): Promise<QueryResult> {
const firestore = await this.getConnection(sourceOptions);
const operation = queryOptions.operation;
let result = {};
2021-07-17 04:41:02 +00:00
try {
switch (operation) {
case 'query_collection':
result = await queryCollection(
firestore,
queryOptions.path,
parseInt(queryOptions.limit),
queryOptions.where_operation,
queryOptions.where_field,
queryOptions.where_value,
queryOptions.order_field,
queryOptions.order_type
);
2021-07-17 04:41:02 +00:00
break;
case 'get_document':
result = await getDocument(firestore, queryOptions.path);
break;
2021-07-17 04:41:02 +00:00
case 'set_document':
result = await setDocument(firestore, queryOptions.path, queryOptions.body);
break;
case 'add_document':
result = await addDocument(firestore, queryOptions.path, queryOptions.body);
break;
2021-07-17 04:41:02 +00:00
case 'update_document':
result = await updateDocument(firestore, queryOptions.path, queryOptions.body);
break;
2021-07-17 04:41:02 +00:00
case 'delete_document':
result = await deleteDocument(firestore, queryOptions.path);
break;
2021-07-17 04:41:02 +00:00
case 'bulk_update':
result = await bulkUpdate(
firestore,
queryOptions.collection,
JSON.parse(queryOptions.records),
queryOptions['document_id_key']
);
break;
2021-07-17 04:41:02 +00:00
}
} catch (error) {
throw new QueryError('Query could not be completed', error.message, {});
}
return {
status: 'ok',
data: result,
};
}
2021-07-18 07:20:46 +00:00
async testConnection(sourceOptions: object): Promise<ConnectionTestResult> {
const client = await this.getConnection(sourceOptions);
await getDocument(client, 'test/test');
return {
status: 'ok',
};
2021-07-18 07:20:46 +00:00
}
async getConnection(sourceOptions: any): Promise<any> {
const gcpKey = parseJson(sourceOptions['gcp_key'], 'GCP key could not be parsed as a valid JSON object');
const firestore = new Firestore({
projectId: gcpKey['project_id'],
credentials: {
private_key: gcpKey['private_key'],
client_email: gcpKey['client_email'],
},
});
return firestore;
}
2021-07-17 04:41:02 +00:00
}