Skip to content

Commit

Permalink
actionscripts saves to document directly
Browse files Browse the repository at this point in the history
  • Loading branch information
shamsmosowi committed Sep 15, 2021
1 parent 5f305c9 commit 9c380b8
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 94 deletions.
179 changes: 91 additions & 88 deletions src/actionScripts/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import * as functions from "firebase-functions";
import * as _ from "lodash";
import { db, auth } from "../firebaseConfig";
import * as admin from "firebase-admin";
import { Request, Response } from 'express'
import { Request, Response } from "express";

//import utilFns from "./utils";
type ActionData = {
Expand Down Expand Up @@ -32,95 +31,99 @@ const generateSchemaDocPath = (tablePath) => {
};
const serverTimestamp = admin.firestore.FieldValue.serverTimestamp;

export const actionScript = async (req:Request,res:Response) => {
try {
const user = res.locals.user;
const { ref, actionParams, column, action, schemaDocPath }:ActionData = req.body;
const _schemaDocPath =
schemaDocPath ?? generateSchemaDocPath(ref.tablePath);
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 res.send({
success: false,
message: "no schema found",
});
}
const config = schemaDocData.columns[column.key].config;
const { script, requiredRoles, requiredFields } = config;
if (!requiredRoles || requiredRoles.length === 0) {
throw Error(`You need to specify at least one role to run this script`);
}
console.log(`requiredRoles: ${requiredRoles}`);
console.log(`userRoles: ${user.customClaims.roles}`)
if (!requiredRoles.some((role) => user.customClaims.roles.includes(role))) {
throw Error(`You don't have the required roles permissions`);
}

const missingRequiredFields = requiredFields
? requiredFields.reduce(missingFieldsReducer(row), [])
: [];
if (missingRequiredFields.length > 0) {
throw new Error(
`Missing required fields:${missingRequiredFields.join(", ")}`
);
}
const result: {
message: string;
status: string;
success: boolean;
} = await eval(
`async({row,db, ref,auth,utilFns,actionParams,context})=>{${
action === "undo" ? config["undo.script"] : script
}}`
)({ row, db, auth,// utilFns,
ref, actionParams, //context
});
if (result.success || result.status) {
const cellValue = {
redo: result.success ? config["redo.enabled"]:true,
status: result.status,
completedAt: serverTimestamp(),
ranBy: user.email,
undo: config["undo.enabled"],
};
try {
const userDoc = await db
.collection("/_rowy_/userManagement/users")
.doc(user.uid)
.get();
const userData = userDoc?.get("user");
await db.doc(ref.path).update({
[column.key]: cellValue,
updatedBy: userData
? {
...userData,
...user,
timestamp: new Date(),
}
: null,
});
} catch (error) {
// if actionScript code deletes the row, it will throw an error when updating the cell
}
export const actionScript = async (req: Request, res: Response) => {
try {
const user = res.locals.user;
const { ref, actionParams, column, action, schemaDocPath }: ActionData =
req.body;
const _schemaDocPath =
schemaDocPath ?? generateSchemaDocPath(ref.tablePath);
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 res.send({
success: false,
message: "no schema found",
});
}
const config = schemaDocData.columns[column.key].config;
const { script, requiredRoles, requiredFields } = config;
if (!requiredRoles || requiredRoles.length === 0) {
throw Error(`You need to specify at least one role to run this script`);
}
console.log(`requiredRoles: ${requiredRoles}`);
console.log(`userRoles: ${user.customClaims.roles}`);
if (!requiredRoles.some((role) => user.customClaims.roles.includes(role))) {
throw Error(`You don't have the required roles permissions`);
}

return res.send({
...result,cellValue
});
}else return res.send({
success: false,
message: result.message,
const missingRequiredFields = requiredFields
? requiredFields.reduce(missingFieldsReducer(row), [])
: [];
if (missingRequiredFields.length > 0) {
throw new Error(
`Missing required fields:${missingRequiredFields.join(", ")}`
);
}
const result: {
message: string;
status: string;
success: boolean;
} = await eval(
`async({row,db, ref,auth,utilFns,actionParams,context})=>{${
action === "undo" ? config["undo.script"] : script
}}`
)({
row,
db,
auth, // utilFns,
ref,
actionParams, //context
});
if (result.success || result.status) {
const cellValue = {
redo: result.success ? config["redo.enabled"] : true,
status: result.status,
completedAt: serverTimestamp(),
ranBy: user.email,
undo: config["undo.enabled"],
};
try {
const userDoc = await db
.collection("/_rowy_/userManagement/users")
.doc(user.uid)
.get();
const userData = userDoc?.get("user");
await db.doc(ref.path).update({
[column.key]: cellValue,
_updatedBy: userData
? {
...userData,
timestamp: admin.firestore.FieldValue.serverTimestamp(),
}
: null,
});
} catch (error:any) {
} catch (error) {
// if actionScript code deletes the row, it will throw an error when updating the cell
console.log(error);
}
return res.send({
...result,
});
} else
return res.send({
success: false,
error,
message: error.message,
message: result.message,
});
}
} catch (error: any) {
return res.send({
success: false,
error,
message: error.message,
});
}

};
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const functionWrapper = (fn) => async (req, res) => {
};
// rowy Run Setup
// get version
app.get('/version',version);
app.get('/version',functionWrapper(version));
app.get('/region',functionWrapper(region));

app.get('/serviceAccountAccess',serviceAccountAccess)
Expand Down
7 changes: 2 additions & 5 deletions src/setup/version.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@

import { Request,Response } from "express";
const meta = require('../../package.json')
export const version = async (req:Request, res:Response) => {

res.send({ version: meta.version,});
}
export const version = async () => ({ version: meta.version})

0 comments on commit 9c380b8

Please sign in to comment.