Skip to content

Commit

Permalink
Merge pull request #271 from AntlerVC/rc
Browse files Browse the repository at this point in the history
v1.2.0: Copy column config from existing table
  • Loading branch information
AntlerEngineering authored Nov 23, 2020
2 parents 75a0f03 + 72e1249 commit 6260061
Show file tree
Hide file tree
Showing 79 changed files with 471 additions and 375 deletions.
Binary file not shown.
12 changes: 0 additions & 12 deletions cloud_functions/functions/firebase-credentials.json.example

This file was deleted.

2 changes: 1 addition & 1 deletion cloud_functions/functions/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
"@google-cloud/storage": "^5.1.2",
"@sendgrid/mail": "^7.2.6",
"@slack/web-api": "^5.11.0",
"algoliasearch": "^3.35.1",
"algoliasearch": "^4.6.0",
"firebase-admin": "^8.9.2",
"firebase-functions": "^3.3.0",
"imagemin": "^7.0.1",
Expand Down
13 changes: 9 additions & 4 deletions cloud_functions/functions/src/actionScript/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ type ActionData = {
tablePath: string;
};
schemaDocPath?: string;
row: any;
column: any;
action: "run" | "redo" | "undo";
actionParams: any;
Expand Down Expand Up @@ -45,11 +44,14 @@ export const actionScript = functions.https.onCall(
throw Error(`You are unauthenticated`);
}

const { ref, actionParams, row, column, action, schemaDocPath } = data;

const { ref, actionParams, column, action, schemaDocPath } = data;
const _schemaDocPath =
schemaDocPath ?? generateSchemaDocPath(ref.tablePath);
const schemaDoc = await db.doc(_schemaDocPath).get();
const [schemaDoc, rowQuery] = await Promise.all([
db.doc(_schemaDocPath).get(),
db.doc(ref.path).get(),
]);
const row = rowQuery.data();
const schemaDocData = schemaDoc.data();
if (!schemaDocData) {
return {
Expand All @@ -59,6 +61,9 @@ export const actionScript = functions.https.onCall(
}
const config = schemaDocData.columns[column.key].config;
const { script, requiredRoles, requiredFields, undo, redo } = config;
if (!requiredRoles || requiredRoles.length === 0) {
throw Error(`You need to specify at least one role to run this script`);
}
if (!hasAnyRole(requiredRoles, context)) {
throw Error(`You don't have the required roles permissions`);
}
Expand Down
4 changes: 2 additions & 2 deletions cloud_functions/functions/src/algolia/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as algoliasearch from "algoliasearch";
import algoliasearch from "algoliasearch";
import * as functions from "firebase-functions";
import * as _ from "lodash";
import { env } from "../config";
Expand Down Expand Up @@ -90,7 +90,7 @@ const addToAlgolia = (
const algoliaData = fieldsToSync.reduce(algoliaReducer(docData), {});
if (Object.keys(algoliaData).length === 0) return false; // returns if theres nothing to sync
const index = client.initIndex(_index); // initialize algolia index
return index.addObject({ ...algoliaData, objectID }); // add new algolia entry
return index.saveObject({ ...algoliaData, objectID }); // add new algolia entry
};

const updateAlgolia = (
Expand Down
42 changes: 32 additions & 10 deletions cloud_functions/functions/src/collectionSync/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,14 @@ const syncDoc = (targetCollection: string, fieldsToSync: string[]) => async (
return true;
};

const deleteDoc = (targetCollection: string) => async (
snapshot: FirebaseFirestore.DocumentSnapshot,
context: functions.EventContext
) => {
const { docId } = context.params;
return db.collection(targetCollection).doc(docId).delete();
};

/**
* onUpdate change to snapshot adapter
* @param targetCollection
Expand Down Expand Up @@ -104,26 +112,40 @@ const syncDocOnUpdate = (

/**
* returns 2 different trigger functions (onCreate,onUpdate) in an object
* @param collection configuration object
* @param collectionConfig configuration object
* onCreate
* onUpdate
* onDelete
* source
* target
* fieldsToSync
*
*/
const collectionSyncFnsGenerator = (collection) =>
const collectionSyncFnsGenerator = (collectionConfig) =>
Object.entries({
onCreate: collection.onCreate
onCreate: collectionConfig.onCreate
? functions.firestore
.document(`${collection.source}/{docId}`)
.onCreate(cloneDoc(collection.target, collection.fieldsToSync))
.document(`${collectionConfig.source}/{docId}`)
.onCreate(
cloneDoc(collectionConfig.target, collectionConfig.fieldsToSync)
)
: null,
onUpdate: collection.onUpdate
onUpdate: collectionConfig.onUpdate
? functions.firestore
.document(`${collection.source}/{docId}`)
.document(`${collectionConfig.source}/{docId}`)
.onUpdate(
syncDocOnUpdate(
collection.target,
collection.fieldsToSync,
collection.forcedUpdate
collectionConfig.target,
collectionConfig.fieldsToSync,
collectionConfig.forcedUpdate
)
)
: null,
onDelete: collectionConfig.onDelete
? functions.firestore
.document(`${collectionConfig.source}/{docId}`)
.onDelete(deleteDoc(collectionConfig.target))
: null,
}).reduce((a, [k, v]) => (v === null ? a : { ...a, [k]: v }), {});

//export default collectionSyncFnsGenerator;
Expand Down
5 changes: 4 additions & 1 deletion cloud_functions/functions/src/derivatives/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,10 @@ export const derivativeOnUpdate = async (
};

export const FT_derivatives = {
[collectionPath.replace("-", "_")]: {
[collectionPath
.replace("-", "_")
.replace(/\//g, "_")
.replace(/_{.*?}_/g, "_")]: {
onUpdate: functions.firestore
.document(`${collectionPath}/{docId}`)
.onUpdate(derivativeOnUpdate),
Expand Down
133 changes: 59 additions & 74 deletions cloud_functions/functions/src/generateConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,85 +4,70 @@ import * as admin from "firebase-admin";
// Initialize Firebase Admin
//const serverTimestamp = admin.firestore.FieldValue.serverTimestamp;

const serviceAccount = requireIfExists("../firebase-credentials.json");

function requireIfExists(module) {
try {
return require(module);
} catch (error) {
console.log("serviceAccount json not found");
return false;
}
}
if (serviceAccount) {
console.log(`Running on ${serviceAccount.project_id}`);
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: `https://${serviceAccount.project_id}.firebaseio.com`,
});

const db = admin.firestore();
const main = async (functionType: string, configString: string) => {
let configData;
switch (functionType) {
case "FT_derivatives":
const schemaDoc = await db
.doc(`_FIRETABLE_/settings/schema/${configString}`)
.get();
const schemaData = schemaDoc.data();
if (!schemaData) return;
const derivativeColumns = Object.values(schemaData.columns).filter(
(col: any) => col.type === "DERIVATIVE"
);
const config = derivativeColumns.reduce((acc, currColumn: any) => {
return `${acc}{
admin.initializeApp();
const db = admin.firestore();
const main = async (functionType: string, configString: string) => {
let configData;
switch (functionType) {
case "FT_derivatives":
const isCollectionGroup = configString.includes("/");
const collectionPath = `${configString}`;
const schemaPath = isCollectionGroup
? `/_FIRETABLE_/settings/groupSchema/${configString.split("/").pop()}`
: `_FIRETABLE_/settings/schema/${collectionPath}`;
const schemaDoc = await db.doc(schemaPath).get();
const schemaData = schemaDoc.data();
if (!schemaData) return;
const derivativeColumns = Object.values(schemaData.columns).filter(
(col: any) => col.type === "DERIVATIVE"
);
const config = derivativeColumns.reduce((acc, currColumn: any) => {
return `${acc}{
fieldName:'${currColumn.key}',eval:(db)=> async ({row,ref}) =>{${
currColumn.config.script
}},listenerFields:[${(currColumn.config.listenerFields ?? [])
.map((f) => `"${f}"`)
.join(",")}]},`;
}, ``);
currColumn.config.script
}},listenerFields:[${(currColumn.config.listenerFields ?? [])
.map((f) => `"${f}"`)
.join(",")}]},`;
}, ``);

configData = `export default [${config}]\nexport const collectionPath ="${configString}"`;
break;
configData = `export default [${config}]\nexport const collectionPath ="${collectionPath}"`;
break;

case "FT_aggregates":
const _schemaDoc = await db
.doc(`_FIRETABLE_/settings/schema/${configString}`)
.get();
const _schemaData = _schemaDoc.data();
if (!_schemaData) return;
const aggregateColumns = Object.values(_schemaData.columns).filter(
(col: any) => col.type === "AGGREGATE"
);
const _config = aggregateColumns.reduce((acc, currColumn: any) => {
return `${acc}{
case "FT_aggregates":
const _schemaDoc = await db
.doc(`_FIRETABLE_/settings/schema/${configString}`)
.get();
const _schemaData = _schemaDoc.data();
if (!_schemaData) return;
const aggregateColumns = Object.values(_schemaData.columns).filter(
(col: any) => col.type === "AGGREGATE"
);
const _config = aggregateColumns.reduce((acc, currColumn: any) => {
return `${acc}{
fieldName:'${
currColumn.key
}',eval:(db)=> async ({aggregateState,incrementor,triggerType,change,afterData,beforeData}) =>{${
currColumn.config.script
}},subtables:[${currColumn.config.subtables
.map((t) => `"${t}"`)
.join(",")}]},`;
}, ``);
currColumn.config.script
}},subtables:[${currColumn.config.subtables
.map((t) => `"${t}"`)
.join(",")}]},`;
}, ``);

configData = `export default [${_config}]\nexport const collectionPath ="${configString}"`;
break;
case "FT_subTableStats":
configData = `export const collectionPath ="${configString}"\nexport default []`;
break;
default:
configData = `export default ${configString}\n export const collectionPath=''`;
break;
}
fs.writeFileSync("./src/functionConfig.ts", configData);
return;
};
configData = `export default [${_config}]\nexport const collectionPath ="${configString}"`;
break;
case "FT_subTableStats":
configData = `export const collectionPath ="${configString}"\nexport default []`;
break;
default:
configData = `export default ${configString}\n export const collectionPath=''`;
break;
}
console.log({ configData });
fs.writeFileSync("./src/functionConfig.ts", configData);
return;
};

main(process.argv[2], process.argv[3])
.catch((err) => console.log(err))
.then(() => console.log("this will succeed"))
.catch(() => "obligatory catch");
} else {
console.log("did not run generator");
}
main(process.argv[2], process.argv[3])
.catch((err) => console.log(err))
.then(() => console.log("this will succeed"))
.catch(() => "obligatory catch");
40 changes: 12 additions & 28 deletions cloud_functions/functions/updateDeployStatus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,18 @@
import * as admin from "firebase-admin";
// Initialize Firebase Admin
const serverTimestamp = admin.firestore.FieldValue.serverTimestamp;
const serviceAccount = requireIfExists(`./firebase-credentials.json`);
admin.initializeApp();
const db = admin.firestore();

function requireIfExists(module) {
try {
return require(module);
} catch (error) {
console.log("serviceAccount json not found");
return false;
}
}
if (serviceAccount) {
console.log(`Running on ${serviceAccount.project_id}`);
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: `https://${serviceAccount.project_id}.firebaseio.com`,
const main = async (deployRequestPath: string, currentBuild) => {
await db.doc(deployRequestPath).update({
deployedAt: serverTimestamp(),
currentBuild: currentBuild ?? "",
});
const db = admin.firestore();
return true;
};

const main = async (deployRequestPath: string, currentBuild) => {
await db.doc(deployRequestPath).update({
deployedAt: serverTimestamp(),
currentBuild: currentBuild ?? "",
});
return true;
};

main(process.argv[2], process.argv[3])
.catch((err) => console.log(err))
.then(() => console.log("this will succeed"))
.catch(() => "obligatory catch");
}
main(process.argv[2], process.argv[3])
.catch((err) => console.log(err))
.then(() => console.log("this will succeed"))
.catch(() => "obligatory catch");
Loading

0 comments on commit 6260061

Please sign in to comment.