diff --git a/packages/auth/src/db/index.js b/packages/auth/src/db/index.js index f94fe4afea..cca0a3ddba 100644 --- a/packages/auth/src/db/index.js +++ b/packages/auth/src/db/index.js @@ -1,9 +1,9 @@ let Pouch -module.exports.setDB = pouch => { +module.exports.setDB = (pouch) => { Pouch = pouch } -module.exports.getDB = dbName => { +module.exports.getDB = (dbName) => { return new Pouch(dbName) } diff --git a/packages/auth/src/db/utils.js b/packages/auth/src/db/utils.js index 393e03e492..de743a7764 100644 --- a/packages/auth/src/db/utils.js +++ b/packages/auth/src/db/utils.js @@ -48,7 +48,7 @@ exports.getGroupParams = (id = "", otherProps = {}) => { * Generates a new global user ID. * @returns {string} The new user ID which the user doc can be stored under. */ -exports.generateGlobalUserID = id => { +exports.generateGlobalUserID = (id) => { return `${DocumentTypes.USER}${SEPARATOR}${id || newid()}` } @@ -70,7 +70,7 @@ exports.getGlobalUserParams = (globalId, otherProps = {}) => { * Generates a template ID. * @param ownerId The owner/user of the template, this could be global or a group level. */ -exports.generateTemplateID = ownerId => { +exports.generateTemplateID = (ownerId) => { return `${DocumentTypes.TEMPLATE}${SEPARATOR}${ownerId}${newid()}` } @@ -123,7 +123,7 @@ const getConfigParams = ({ type, group, user }, otherProps = {}) => { * @param {Object} scopes - the type, group and userID scopes of the configuration. * @returns The most granular configuration document based on the scope. */ -const determineScopedConfig = async function(db, { type, user, group }) { +const determineScopedConfig = async function (db, { type, user, group }) { const response = await db.allDocs( getConfigParams( { type, user, group }, @@ -132,7 +132,7 @@ const determineScopedConfig = async function(db, { type, user, group }) { } ) ) - const configs = response.rows.map(row => { + const configs = response.rows.map((row) => { const config = row.doc // Config is specific to a user and a group diff --git a/packages/auth/src/hashing.js b/packages/auth/src/hashing.js index 65976fc1f3..fe9b034c63 100644 --- a/packages/auth/src/hashing.js +++ b/packages/auth/src/hashing.js @@ -4,7 +4,7 @@ const { v4 } = require("uuid") const SALT_ROUNDS = env.SALT_ROUNDS || 10 -exports.hash = async data => { +exports.hash = async (data) => { const salt = await bcrypt.genSalt(SALT_ROUNDS) return bcrypt.hash(data, salt) } @@ -13,6 +13,6 @@ exports.compare = async (data, encrypted) => { return bcrypt.compare(data, encrypted) } -exports.newid = function() { +exports.newid = function () { return v4().replace(/-/g, "") } diff --git a/packages/auth/src/middleware/passport/google.js b/packages/auth/src/middleware/passport/google.js index 968dfa3e93..407772ebf0 100644 --- a/packages/auth/src/middleware/passport/google.js +++ b/packages/auth/src/middleware/passport/google.js @@ -51,7 +51,7 @@ async function authenticate(token, tokenSecret, profile, done) { * from couchDB rather than environment variables, using this factory is necessary for dynamically configuring passport. * @returns Dynamically configured Passport Google Strategy */ -exports.strategyFactory = async function(config) { +exports.strategyFactory = async function (config) { try { const { clientID, clientSecret, callbackURL } = config diff --git a/packages/auth/src/middleware/passport/jwt.js b/packages/auth/src/middleware/passport/jwt.js index fdff3f3cfc..ed7d179482 100644 --- a/packages/auth/src/middleware/passport/jwt.js +++ b/packages/auth/src/middleware/passport/jwt.js @@ -3,12 +3,12 @@ const env = require("../../environment") exports.options = { secretOrKey: env.JWT_SECRET, - jwtFromRequest: function(ctx) { + jwtFromRequest: function (ctx) { return ctx.cookies.get(Cookies.Auth) }, } -exports.authenticate = async function(jwt, done) { +exports.authenticate = async function (jwt, done) { try { return done(null, jwt) } catch (err) { diff --git a/packages/auth/src/middleware/passport/local.js b/packages/auth/src/middleware/passport/local.js index 5b8bf307d7..0f5cb82606 100644 --- a/packages/auth/src/middleware/passport/local.js +++ b/packages/auth/src/middleware/passport/local.js @@ -15,7 +15,7 @@ exports.options = {} * @param {*} done - callback from passport to return user information and errors * @returns The authenticated user, or errors if they occur */ -exports.authenticate = async function(email, password, done) { +exports.authenticate = async function (email, password, done) { if (!email) return done(null, false, "Email Required.") if (!password) return done(null, false, "Password Required.") diff --git a/packages/auth/src/utils.js b/packages/auth/src/utils.js index 10507410b1..beb1c33cf1 100644 --- a/packages/auth/src/utils.js +++ b/packages/auth/src/utils.js @@ -22,7 +22,7 @@ function confirmAppId(possibleAppId) { * @param {object} ctx The main request body to look through. * @returns {string|undefined} If an appId was found it will be returned. */ -exports.getAppId = ctx => { +exports.getAppId = (ctx) => { const options = [ctx.headers["x-budibase-app-id"], ctx.params.appId] if (ctx.subdomains) { options.push(ctx.subdomains[1]) @@ -41,7 +41,7 @@ exports.getAppId = ctx => { } let appPath = ctx.request.headers.referrer || - ctx.path.split("/").filter(subPath => subPath.startsWith(APP_PREFIX)) + ctx.path.split("/").filter((subPath) => subPath.startsWith(APP_PREFIX)) if (!appId && appPath.length !== 0) { appId = confirmAppId(appPath[0]) } @@ -101,11 +101,11 @@ exports.clearCookie = (ctx, name) => { * @param {object} ctx The koa context object to be tested. * @return {boolean} returns true if the call is from the client lib (a built app rather than the builder). */ -exports.isClient = ctx => { +exports.isClient = (ctx) => { return ctx.headers["x-budibase-type"] === "client" } -exports.getGlobalUserByEmail = async email => { +exports.getGlobalUserByEmail = async (email) => { const db = getDB(StaticDatabases.GLOBAL.name) try { let users = ( @@ -114,7 +114,7 @@ exports.getGlobalUserByEmail = async email => { include_docs: true, }) ).rows - users = users.map(user => user.doc) + users = users.map((user) => user.doc) return users.length <= 1 ? users[0] : users } catch (err) { if (err != null && err.name === "not_found") { diff --git a/packages/bbui/src/Actions/position_dropdown.js b/packages/bbui/src/Actions/position_dropdown.js index a25cc1bbd5..776fc7f83e 100644 --- a/packages/bbui/src/Actions/position_dropdown.js +++ b/packages/bbui/src/Actions/position_dropdown.js @@ -47,7 +47,7 @@ export default function positionDropdown(element, { anchor, align }) { element.style[positionSide] = `${dimensions[positionSide]}px` element.style.left = `${calcLeftPosition(dimensions).toFixed(0)}px` - const resizeObserver = new ResizeObserver(entries => { + const resizeObserver = new ResizeObserver((entries) => { entries.forEach(() => { dimensions = getDimensions() element.style[positionSide] = `${dimensions[positionSide]}px` diff --git a/packages/bbui/src/Stores/notifications.js b/packages/bbui/src/Stores/notifications.js index 761d8531ec..0f397f4dba 100644 --- a/packages/bbui/src/Stores/notifications.js +++ b/packages/bbui/src/Stores/notifications.js @@ -7,7 +7,7 @@ export const createNotificationStore = () => { const _notifications = writable([], () => { return () => { // clear all the timers - timeoutIds.forEach(timeoutId => { + timeoutIds.forEach((timeoutId) => { clearTimeout(timeoutId) }) _notifications.set([]) @@ -25,11 +25,11 @@ export const createNotificationStore = () => { return } let _id = id() - _notifications.update(state => { + _notifications.update((state) => { return [...state, { id: _id, type, message, icon }] }) const timeoutId = setTimeout(() => { - _notifications.update(state => { + _notifications.update((state) => { return state.filter(({ id }) => id !== _id) }) }, NOTIFICATION_TIMEOUT) @@ -41,21 +41,16 @@ export const createNotificationStore = () => { return { subscribe, send, - info: msg => send(msg, "info", "Info"), - error: msg => send(msg, "error", "Alert"), - warning: msg => send(msg, "warning", "Alert"), - success: msg => send(msg, "success", "CheckmarkCircle"), + info: (msg) => send(msg, "info", "Info"), + error: (msg) => send(msg, "error", "Alert"), + warning: (msg) => send(msg, "warning", "Alert"), + success: (msg) => send(msg, "success", "CheckmarkCircle"), blockNotifications, } } function id() { - return ( - "_" + - Math.random() - .toString(36) - .substr(2, 9) - ) + return "_" + Math.random().toString(36).substr(2, 9) } export const notifications = createNotificationStore() diff --git a/packages/bbui/src/utils/helpers.js b/packages/bbui/src/utils/helpers.js index 0dc9f9801e..13531d7f09 100644 --- a/packages/bbui/src/utils/helpers.js +++ b/packages/bbui/src/utils/helpers.js @@ -1,7 +1,5 @@ export const generateID = () => { - const rand = Math.random() - .toString(32) - .substring(2) + const rand = Math.random().toString(32).substring(2) // Starts with a letter so that its a valid DOM ID return `A${rand}` diff --git a/packages/builder/build/copy.js b/packages/builder/build/copy.js index eecc46736f..f3077b7854 100644 --- a/packages/builder/build/copy.js +++ b/packages/builder/build/copy.js @@ -1,6 +1,6 @@ const ncp = require("ncp").ncp -ncp("./dist", "../server/builder", function(err) { +ncp("./dist", "../server/builder", function (err) { if (err) { return console.error(err) } diff --git a/packages/builder/cypress/support/commands.js b/packages/builder/cypress/support/commands.js index a1ff468d8a..57a5fe16de 100644 --- a/packages/builder/cypress/support/commands.js +++ b/packages/builder/cypress/support/commands.js @@ -6,15 +6,13 @@ // Cypress.Commands.add("login", () => { - cy.getCookie("budibase:auth").then(cookie => { + cy.getCookie("budibase:auth").then((cookie) => { // Already logged in if (cookie) return cy.visit(`localhost:${Cypress.env("PORT")}/builder`) cy.contains("Create Test User").click() - cy.get("input") - .first() - .type("test@test.com") + cy.get("input").first().type("test@test.com") cy.get('input[type="password"]').type("test") @@ -22,38 +20,26 @@ Cypress.Commands.add("login", () => { }) }) -Cypress.Commands.add("createApp", name => { +Cypress.Commands.add("createApp", (name) => { cy.visit(`localhost:${Cypress.env("PORT")}/builder`) // wait for init API calls on visit cy.wait(100) cy.contains("Create New Web App").click() cy.get("body") - .then($body => { + .then(($body) => { if ($body.find("input[name=apiKey]").length) { // input was found, do something else here - cy.get("input[name=apiKey]") - .type(name) - .should("have.value", name) + cy.get("input[name=apiKey]").type(name).should("have.value", name) cy.contains("Next").click() } }) .then(() => { cy.get(".spectrum-Modal") .within(() => { - cy.get("input") - .eq(0) - .type(name) - .should("have.value", name) - .blur() + cy.get("input").eq(0).type(name).should("have.value", name).blur() cy.contains("Next").click() - cy.get("input") - .eq(1) - .type("test@test.com") - .blur() - cy.get("input") - .eq(2) - .type("test") - .blur() + cy.get("input").eq(1).type("test@test.com").blur() + cy.get("input").eq(2).type("test").blur() cy.contains("Submit").click() }) .then(() => { @@ -64,20 +50,16 @@ Cypress.Commands.add("createApp", name => { }) }) -Cypress.Commands.add("deleteApp", name => { +Cypress.Commands.add("deleteApp", (name) => { cy.visit(`localhost:${Cypress.env("PORT")}/builder`) - cy.get(".apps").then($apps => { + cy.get(".apps").then(($apps) => { cy.wait(1000) if ($apps.find(`[data-cy="app-${name}"]`).length) { - cy.get(`[data-cy="app-${name}"]`) - .contains("Open") - .click() + cy.get(`[data-cy="app-${name}"]`).contains("Open").click() cy.get("[data-cy=settings-icon]").click() cy.get(".spectrum-Dialog").within(() => { cy.contains("Danger Zone").click() - cy.get("input") - .type("DELETE") - .blur() + cy.get("input").type("DELETE").blur() cy.contains("Delete Entire App").click() }) } @@ -96,17 +78,12 @@ Cypress.Commands.add("createTestTableWithData", () => { cy.addColumn("dog", "age", "Number") }) -Cypress.Commands.add("createTable", tableName => { +Cypress.Commands.add("createTable", (tableName) => { // Enter table name cy.get("[data-cy=new-table]").click() cy.get(".spectrum-Modal").within(() => { - cy.get("input") - .first() - .type(tableName) - .blur() - cy.get(".spectrum-ButtonGroup") - .contains("Create") - .click() + cy.get("input").first().type(tableName).blur() + cy.get(".spectrum-ButtonGroup").contains("Create").click() }) cy.contains(tableName).should("be.visible") }) @@ -118,10 +95,7 @@ Cypress.Commands.add("addColumn", (tableName, columnName, type) => { // Configure column cy.get(".spectrum-Modal").within(() => { - cy.get("input") - .first() - .type(columnName) - .blur() + cy.get("input").first().type(columnName).blur() // Unset table display column cy.contains("display column").click({ force: true }) @@ -130,18 +104,13 @@ Cypress.Commands.add("addColumn", (tableName, columnName, type) => { }) }) -Cypress.Commands.add("addRow", values => { +Cypress.Commands.add("addRow", (values) => { cy.contains("Create row").click() cy.get(".spectrum-Modal").within(() => { for (let i = 0; i < values.length; i++) { - cy.get("input") - .eq(i) - .type(values[i]) - .blur() + cy.get("input").eq(i).type(values[i]).blur() } - cy.get(".spectrum-ButtonGroup") - .contains("Create") - .click() + cy.get(".spectrum-ButtonGroup").contains("Create").click() }) }) @@ -150,22 +119,12 @@ Cypress.Commands.add("createUser", (email, password, role) => { cy.contains("Users").click() cy.contains("Create user").click() cy.get(".spectrum-Modal").within(() => { - cy.get("input") - .first() - .type(email) - .blur() - cy.get("input") - .eq(1) - .type(password) - .blur() - cy.get("select") - .first() - .select(role) + cy.get("input").first().type(email).blur() + cy.get("input").eq(1).type(password).blur() + cy.get("select").first().select(role) // Save - cy.get(".spectrum-ButtonGroup") - .contains("Create User") - .click() + cy.get(".spectrum-ButtonGroup").contains("Create User").click() }) }) @@ -175,7 +134,7 @@ Cypress.Commands.add("addComponent", (category, component) => { } cy.get(`[data-cy="component-${component}"]`).click() cy.wait(1000) - cy.location().then(loc => { + cy.location().then((loc) => { const params = loc.pathname.split("/") const componentId = params[params.length - 1] cy.getComponent(componentId).should("exist") @@ -183,7 +142,7 @@ Cypress.Commands.add("addComponent", (category, component) => { }) }) -Cypress.Commands.add("getComponent", componentId => { +Cypress.Commands.add("getComponent", (componentId) => { return cy .get("iframe") .its("0.contentDocument") @@ -201,15 +160,9 @@ Cypress.Commands.add("navigateToFrontend", () => { Cypress.Commands.add("createScreen", (screenName, route) => { cy.get("[data-cy=new-screen]").click() cy.get(".spectrum-Modal").within(() => { - cy.get("input") - .eq(0) - .type(screenName) - .blur() + cy.get("input").eq(0).type(screenName).blur() if (route) { - cy.get("input") - .eq(1) - .type(route) - .blur() + cy.get("input").eq(1).type(route).blur() } cy.contains("Create Screen").click() }) diff --git a/packages/builder/src/analytics.js b/packages/builder/src/analytics.js index e6a647a08b..f801eb84db 100644 --- a/packages/builder/src/analytics.js +++ b/packages/builder/src/analytics.js @@ -32,7 +32,7 @@ function identify(id) { if (!analyticsEnabled || !id) return if (posthogConfigured) posthog.identify(id) if (sentryConfigured) - Sentry.configureScope(scope => { + Sentry.configureScope((scope) => { scope.setUser({ id: id }) }) } @@ -73,7 +73,7 @@ if (!localStorage.getItem(APP_FIRST_STARTED_KEY)) { localStorage.setItem(APP_FIRST_STARTED_KEY, Date.now()) } -const isFeedbackTimeElapsed = sinceDateStr => { +const isFeedbackTimeElapsed = (sinceDateStr) => { const sinceDate = parseFloat(sinceDateStr) const feedbackMilliseconds = feedbackHours * 60 * 60 * 1000 return Date.now() > sinceDate + feedbackMilliseconds @@ -107,7 +107,7 @@ function highlightFeedbackIcon() { } // Opt In/Out -const ifAnalyticsEnabled = func => () => { +const ifAnalyticsEnabled = (func) => () => { if (analyticsEnabled && process.env.POSTHOG_TOKEN) { return func() } diff --git a/packages/builder/src/builderStore/api.js b/packages/builder/src/builderStore/api.js index 2e683238bc..a9244bfa6a 100644 --- a/packages/builder/src/builderStore/api.js +++ b/packages/builder/src/builderStore/api.js @@ -2,7 +2,7 @@ import { store } from "./index" import { get as svelteGet } from "svelte/store" import { removeCookie, Cookies } from "./cookies" -const apiCall = method => async ( +const apiCall = (method) => async ( url, body, headers = { "Content-Type": "application/json" } diff --git a/packages/builder/src/builderStore/cookies.js b/packages/builder/src/builderStore/cookies.js index a84f1a4f20..2966087524 100644 --- a/packages/builder/src/builderStore/cookies.js +++ b/packages/builder/src/builderStore/cookies.js @@ -4,7 +4,7 @@ export const Cookies = { } export function getCookie(cookieName) { - return document.cookie.split(";").some(cookie => { + return document.cookie.split(";").some((cookie) => { return cookie.trim().startsWith(`${cookieName}=`) }) } diff --git a/packages/builder/src/builderStore/dataBinding.js b/packages/builder/src/builderStore/dataBinding.js index 58c4d8f4b6..633f56176e 100644 --- a/packages/builder/src/builderStore/dataBinding.js +++ b/packages/builder/src/builderStore/dataBinding.js @@ -34,7 +34,7 @@ export const getDataProviderComponents = (asset, componentId) => { path.pop() // Filter by only data provider components - return path.filter(component => { + return path.filter((component) => { const def = store.actions.components.getDefinition(component._component) return def?.context != null }) @@ -54,7 +54,7 @@ export const getActionProviderComponents = (asset, componentId, actionType) => { path.pop() // Filter by only data provider components - return path.filter(component => { + return path.filter((component) => { const def = store.actions.components.getDefinition(component._component) return def?.actions?.includes(actionType) }) @@ -70,7 +70,7 @@ export const getDatasourceForProvider = (asset, component) => { } // If this component has a dataProvider setting, go up the stack and use it - const dataProviderSetting = def.settings.find(setting => { + const dataProviderSetting = def.settings.find((setting) => { return setting.type === "dataProvider" }) if (dataProviderSetting) { @@ -82,7 +82,7 @@ export const getDatasourceForProvider = (asset, component) => { // Extract datasource from component instance const validSettingTypes = ["dataSource", "table", "schema"] - const datasourceSetting = def.settings.find(setting => { + const datasourceSetting = def.settings.find((setting) => { return validSettingTypes.includes(setting.type) }) if (!datasourceSetting) { @@ -112,7 +112,7 @@ const getContextBindings = (asset, componentId) => { let bindings = [] // Create bindings for each data provider - dataProviders.forEach(component => { + dataProviders.forEach((component) => { const def = store.actions.components.getDefinition(component._component) const contextDefinition = def.context let schema @@ -127,7 +127,7 @@ const getContextBindings = (asset, componentId) => { // Static contexts are fully defined by the components schema = {} const values = contextDefinition.values || [] - values.forEach(value => { + values.forEach((value) => { schema[value.key] = { name: value.label, type: "string" } }) } else if (contextDefinition.type === "schema") { @@ -148,7 +148,7 @@ const getContextBindings = (asset, componentId) => { // Create bindable properties for each schema field const safeComponentId = makePropSafe(component._id) - keys.forEach(key => { + keys.forEach((key) => { const fieldSchema = schema[key] // Make safe runtime binding and replace certain bindings with a @@ -197,7 +197,7 @@ const getUserBindings = () => { }) const keys = Object.keys(schema).sort() const safeUser = makePropSafe("user") - keys.forEach(key => { + keys.forEach((key) => { const fieldSchema = schema[key] // Replace certain bindings with a new property to help display components let runtimeBoundKey = key @@ -224,17 +224,17 @@ const getUserBindings = () => { /** * Gets all bindable properties from URL parameters. */ -const getUrlBindings = asset => { +const getUrlBindings = (asset) => { const url = asset?.routing?.route ?? "" const split = url.split("/") let params = [] - split.forEach(part => { + split.forEach((part) => { if (part.startsWith(":") && part.length > 1) { params.push(part.replace(/:/g, "").replace(/\?/g, "")) } }) const safeURL = makePropSafe("url") - return params.map(param => ({ + return params.map((param) => ({ type: "context", runtimeBinding: `${safeURL}.${makePropSafe(param)}`, readableBinding: `URL.${param}`, @@ -250,10 +250,10 @@ export const getSchemaForDatasource = (datasource, isForm = false) => { const { type } = datasource if (type === "query") { const queries = get(queriesStores).list - table = queries.find(query => query._id === datasource._id) + table = queries.find((query) => query._id === datasource._id) } else { const tables = get(tablesStore).list - table = tables.find(table => table._id === datasource.tableId) + table = tables.find((table) => table._id === datasource.tableId) } if (table) { if (type === "view") { @@ -261,7 +261,7 @@ export const getSchemaForDatasource = (datasource, isForm = false) => { } else if (type === "query" && isForm) { schema = {} const params = table.parameters || [] - params.forEach(param => { + params.forEach((param) => { if (param?.name) { schema[param.name] = { ...param, type: "string" } } @@ -279,7 +279,7 @@ export const getSchemaForDatasource = (datasource, isForm = false) => { // Ensure there are "name" properties for all fields if (schema) { - Object.keys(schema).forEach(field => { + Object.keys(schema).forEach((field) => { if (!schema[field].name) { schema[field].name = field } @@ -293,14 +293,14 @@ export const getSchemaForDatasource = (datasource, isForm = false) => { * Builds a form schema given a form component. * A form schema is a schema of all the fields nested anywhere within a form. */ -const buildFormSchema = component => { +const buildFormSchema = (component) => { let schema = {} if (!component) { return schema } const def = store.actions.components.getDefinition(component._component) const fieldSetting = def?.settings?.find( - setting => setting.key === "field" && setting.type.startsWith("field/") + (setting) => setting.key === "field" && setting.type.startsWith("field/") ) if (fieldSetting && component.field) { const type = fieldSetting.type.split("field/")[1] @@ -308,7 +308,7 @@ const buildFormSchema = component => { schema[component.field] = { type } } } - component._children?.forEach(child => { + component._children?.forEach((child) => { const childSchema = buildFormSchema(child) schema = { ...schema, ...childSchema } }) @@ -339,7 +339,7 @@ function bindingReplacement(bindableProperties, textWithBindings, convertTo) { return textWithBindings } const convertFromProps = bindableProperties - .map(el => el[convertFrom]) + .map((el) => el[convertFrom]) .sort((a, b) => { return b.length - a.length }) @@ -349,7 +349,9 @@ function bindingReplacement(bindableProperties, textWithBindings, convertTo) { let newBoundValue = boundValue for (let from of convertFromProps) { if (newBoundValue.includes(from)) { - const binding = bindableProperties.find(el => el[convertFrom] === from) + const binding = bindableProperties.find( + (el) => el[convertFrom] === from + ) newBoundValue = newBoundValue.replace(from, binding[convertTo]) } } diff --git a/packages/builder/src/builderStore/index.js b/packages/builder/src/builderStore/index.js index 6fecda84c0..e3ed25b92e 100644 --- a/packages/builder/src/builderStore/index.js +++ b/packages/builder/src/builderStore/index.js @@ -12,12 +12,16 @@ export const automationStore = getAutomationStore() export const themeStore = getThemeStore() export const hostingStore = getHostingStore() -export const currentAsset = derived(store, $store => { +export const currentAsset = derived(store, ($store) => { const type = $store.currentFrontEndType if (type === FrontendTypes.SCREEN) { - return $store.screens.find(screen => screen._id === $store.selectedScreenId) + return $store.screens.find( + (screen) => screen._id === $store.selectedScreenId + ) } else if (type === FrontendTypes.LAYOUT) { - return $store.layouts.find(layout => layout._id === $store.selectedLayoutId) + return $store.layouts.find( + (layout) => layout._id === $store.selectedLayoutId + ) } return null }) @@ -32,24 +36,24 @@ export const selectedComponent = derived( } ) -export const currentAssetId = derived(store, $store => { +export const currentAssetId = derived(store, ($store) => { return $store.currentFrontEndType === FrontendTypes.SCREEN ? $store.selectedScreenId : $store.selectedLayoutId }) -export const currentAssetName = derived(currentAsset, $currentAsset => { +export const currentAssetName = derived(currentAsset, ($currentAsset) => { return $currentAsset?.name }) // leave this as before for consistency -export const allScreens = derived(store, $store => { +export const allScreens = derived(store, ($store) => { return $store.screens }) -export const mainLayout = derived(store, $store => { +export const mainLayout = derived(store, ($store) => { return $store.layouts?.find( - layout => layout._id === LAYOUT_NAMES.MASTER.PRIVATE + (layout) => layout._id === LAYOUT_NAMES.MASTER.PRIVATE ) }) diff --git a/packages/builder/src/builderStore/loadComponentLibraries.js b/packages/builder/src/builderStore/loadComponentLibraries.js index 8bdfcf7538..be8ce41d24 100644 --- a/packages/builder/src/builderStore/loadComponentLibraries.js +++ b/packages/builder/src/builderStore/loadComponentLibraries.js @@ -5,7 +5,7 @@ import { get } from "builderStore/api" * their props and other metadata from components.json. * @param {string} appId - ID of the currently running app */ -export const fetchComponentLibDefinitions = async appId => { +export const fetchComponentLibDefinitions = async (appId) => { const LIB_DEFINITION_URL = `/api/${appId}/components/definitions` try { const libDefinitionResponse = await get(LIB_DEFINITION_URL) diff --git a/packages/builder/src/builderStore/store/automation/Automation.js b/packages/builder/src/builderStore/store/automation/Automation.js index a9dce88258..89f6c2f9af 100644 --- a/packages/builder/src/builderStore/store/automation/Automation.js +++ b/packages/builder/src/builderStore/store/automation/Automation.js @@ -37,7 +37,7 @@ export default class Automation { return } - const stepIdx = steps.findIndex(step => step.id === id) + const stepIdx = steps.findIndex((step) => step.id === id) if (stepIdx < 0) throw new Error("Block not found.") steps.splice(stepIdx, 1, updatedBlock) this.automation.definition.steps = steps @@ -51,7 +51,7 @@ export default class Automation { return } - const stepIdx = steps.findIndex(step => step.id === id) + const stepIdx = steps.findIndex((step) => step.id === id) if (stepIdx < 0) throw new Error("Block not found.") steps.splice(stepIdx, 1) this.automation.definition.steps = steps diff --git a/packages/builder/src/builderStore/store/automation/index.js b/packages/builder/src/builderStore/store/automation/index.js index 7a01bccfab..4b75f12abb 100644 --- a/packages/builder/src/builderStore/store/automation/index.js +++ b/packages/builder/src/builderStore/store/automation/index.js @@ -4,14 +4,14 @@ import Automation from "./Automation" import { cloneDeep } from "lodash/fp" import analytics from "analytics" -const automationActions = store => ({ +const automationActions = (store) => ({ fetch: async () => { const responses = await Promise.all([ api.get(`/api/automations`), api.get(`/api/automations/definitions/list`), ]) - const jsonResponses = await Promise.all(responses.map(x => x.json())) - store.update(state => { + const jsonResponses = await Promise.all(responses.map((x) => x.json())) + store.update((state) => { let selected = state.selectedAutomation?.automation state.automations = jsonResponses[0] state.blockDefinitions = { @@ -22,7 +22,7 @@ const automationActions = store => ({ // if previously selected find the new obj and select it if (selected) { selected = jsonResponses[0].filter( - automation => automation._id === selected._id + (automation) => automation._id === selected._id ) state.selectedAutomation = new Automation(selected[0]) } @@ -40,7 +40,7 @@ const automationActions = store => ({ const CREATE_AUTOMATION_URL = `/api/automations` const response = await api.post(CREATE_AUTOMATION_URL, automation) const json = await response.json() - store.update(state => { + store.update((state) => { state.automations = [...state.automations, json.automation] store.actions.select(json.automation) return state @@ -50,9 +50,9 @@ const automationActions = store => ({ const UPDATE_AUTOMATION_URL = `/api/automations` const response = await api.put(UPDATE_AUTOMATION_URL, automation) const json = await response.json() - store.update(state => { + store.update((state) => { const existingIdx = state.automations.findIndex( - existing => existing._id === automation._id + (existing) => existing._id === automation._id ) state.automations.splice(existingIdx, 1, json.automation) state.automations = state.automations @@ -65,9 +65,9 @@ const automationActions = store => ({ const DELETE_AUTOMATION_URL = `/api/automations/${_id}/${_rev}` await api.delete(DELETE_AUTOMATION_URL) - store.update(state => { + store.update((state) => { const existingIdx = state.automations.findIndex( - existing => existing._id === _id + (existing) => existing._id === _id ) state.automations.splice(existingIdx, 1) state.automations = state.automations @@ -81,15 +81,15 @@ const automationActions = store => ({ const TRIGGER_AUTOMATION_URL = `/api/automations/${_id}/trigger` return await api.post(TRIGGER_AUTOMATION_URL) }, - select: automation => { - store.update(state => { + select: (automation) => { + store.update((state) => { state.selectedAutomation = new Automation(cloneDeep(automation)) state.selectedBlock = null return state }) }, - addBlockToAutomation: block => { - store.update(state => { + addBlockToAutomation: (block) => { + store.update((state) => { const newBlock = state.selectedAutomation.addBlock(cloneDeep(block)) state.selectedBlock = newBlock return state @@ -98,10 +98,10 @@ const automationActions = store => ({ name: block.name, }) }, - deleteAutomationBlock: block => { - store.update(state => { + deleteAutomationBlock: (block) => { + store.update((state) => { const idx = state.selectedAutomation.automation.definition.steps.findIndex( - x => x.id === block.id + (x) => x.id === block.id ) state.selectedAutomation.deleteBlock(block.id) diff --git a/packages/builder/src/builderStore/store/frontend.js b/packages/builder/src/builderStore/store/frontend.js index be553066b9..92a1a3015b 100644 --- a/packages/builder/src/builderStore/store/frontend.js +++ b/packages/builder/src/builderStore/store/frontend.js @@ -49,10 +49,10 @@ export const getFrontendStore = () => { const store = writable({ ...INITIAL_FRONTEND_STATE }) store.actions = { - initialise: async pkg => { + initialise: async (pkg) => { const { layouts, screens, application, clientLibPath } = pkg const components = await fetchComponentLibDefinitions(application._id) - store.update(state => ({ + store.update((state) => ({ ...state, libraries: application.componentLibraries, components, @@ -70,7 +70,7 @@ export const getFrontendStore = () => { // Initialise backend stores const [_integrations] = await Promise.all([ - api.get("/api/integrations").then(r => r.json()), + api.get("/api/integrations").then((r) => r.json()), ]) datasources.init() integrations.set(_integrations) @@ -82,18 +82,18 @@ export const getFrontendStore = () => { fetch: async () => { const response = await api.get("/api/routing") const json = await response.json() - store.update(state => { + store.update((state) => { state.routes = json.routes return state }) }, }, screens: { - select: screenId => { - store.update(state => { + select: (screenId) => { + store.update((state) => { let screens = get(allScreens) let screen = - screens.find(screen => screen._id === screenId) || screens[0] + screens.find((screen) => screen._id === screenId) || screens[0] if (!screen) return state // Update role to the screen's role setting so that it will always @@ -107,9 +107,9 @@ export const getFrontendStore = () => { return state }) }, - create: async screen => { + create: async (screen) => { screen = await store.actions.screens.save(screen) - store.update(state => { + store.update((state) => { state.selectedScreenId = screen._id state.selectedComponentId = screen.props._id state.currentFrontEndType = FrontendTypes.SCREEN @@ -118,15 +118,15 @@ export const getFrontendStore = () => { }) return screen }, - save: async screen => { + save: async (screen) => { const creatingNewScreen = screen._id === undefined const response = await api.post(`/api/screens`, screen) screen = await response.json() await store.actions.routing.fetch() - store.update(state => { + store.update((state) => { const foundScreen = state.screens.findIndex( - el => el._id === screen._id + (el) => el._id === screen._id ) if (foundScreen !== -1) { state.screens.splice(foundScreen, 1) @@ -141,14 +141,14 @@ export const getFrontendStore = () => { return screen }, - delete: async screens => { + delete: async (screens) => { const screensToDelete = Array.isArray(screens) ? screens : [screens] const screenDeletePromises = [] - store.update(state => { + store.update((state) => { for (let screenToDelete of screensToDelete) { state.screens = state.screens.filter( - screen => screen._id !== screenToDelete._id + (screen) => screen._id !== screenToDelete._id ) screenDeletePromises.push( api.delete( @@ -177,8 +177,8 @@ export const getFrontendStore = () => { }, }, layouts: { - select: layoutId => { - store.update(state => { + select: (layoutId) => { + store.update((state) => { const layout = store.actions.layouts.find(layoutId) || get(store).layouts[0] if (!layout) return @@ -189,15 +189,15 @@ export const getFrontendStore = () => { return state }) }, - save: async layout => { + save: async (layout) => { const layoutToSave = cloneDeep(layout) const creatingNewLayout = layoutToSave._id === undefined const response = await api.post(`/api/layouts`, layoutToSave) const savedLayout = await response.json() - store.update(state => { + store.update((state) => { const layoutIdx = state.layouts.findIndex( - stateLayout => stateLayout._id === savedLayout._id + (stateLayout) => stateLayout._id === savedLayout._id ) if (layoutIdx >= 0) { // update existing layout @@ -216,14 +216,14 @@ export const getFrontendStore = () => { return savedLayout }, - find: layoutId => { + find: (layoutId) => { if (!layoutId) { return get(mainLayout) } const storeContents = get(store) - return storeContents.layouts.find(layout => layout._id === layoutId) + return storeContents.layouts.find((layout) => layout._id === layoutId) }, - delete: async layoutToDelete => { + delete: async (layoutToDelete) => { const response = await api.delete( `/api/layouts/${layoutToDelete._id}/${layoutToDelete._rev}` ) @@ -231,9 +231,9 @@ export const getFrontendStore = () => { const json = await response.json() throw new Error(json.message) } - store.update(state => { + store.update((state) => { state.layouts = state.layouts.filter( - layout => layout._id !== layoutToDelete._id + (layout) => layout._id !== layoutToDelete._id ) if (layoutToDelete._id === state.selectedLayoutId) { state.selectedLayoutId = get(mainLayout)._id @@ -243,7 +243,7 @@ export const getFrontendStore = () => { }, }, components: { - select: component => { + select: (component) => { if (!component) { return } @@ -263,13 +263,13 @@ export const getFrontendStore = () => { } // Otherwise select the component - store.update(state => { + store.update((state) => { state.selectedComponentId = component._id state.currentView = "component" return state }) }, - getDefinition: componentName => { + getDefinition: (componentName) => { if (!componentName) { return null } @@ -287,7 +287,7 @@ export const getFrontendStore = () => { // Generate default props let props = { ...presetProps } if (definition.settings) { - definition.settings.forEach(setting => { + definition.settings.forEach((setting) => { if (setting.defaultValue !== undefined) { props[setting.key] = setting.defaultValue } @@ -367,7 +367,7 @@ export const getFrontendStore = () => { // Save components and update UI await store.actions.preview.saveSelected() - store.update(state => { + store.update((state) => { state.currentView = "component" state.selectedComponentId = componentInstance._id return state @@ -380,7 +380,7 @@ export const getFrontendStore = () => { return componentInstance }, - delete: async component => { + delete: async (component) => { if (!component) { return } @@ -391,7 +391,7 @@ export const getFrontendStore = () => { const parent = findComponentParent(asset.props, component._id) if (parent) { parent._children = parent._children.filter( - child => child._id !== component._id + (child) => child._id !== component._id ) store.actions.components.select(parent) } @@ -404,7 +404,7 @@ export const getFrontendStore = () => { } // Update store with copied component - store.update(state => { + store.update((state) => { state.componentToPaste = cloneDeep(component) state.componentToPaste.isCut = cut return state @@ -415,7 +415,7 @@ export const getFrontendStore = () => { const parent = findComponentParent(selectedAsset.props, component._id) if (parent) { parent._children = parent._children.filter( - child => child._id !== component._id + (child) => child._id !== component._id ) store.actions.components.select(parent) } @@ -423,7 +423,7 @@ export const getFrontendStore = () => { }, paste: async (targetComponent, mode) => { let promises = [] - store.update(state => { + store.update((state) => { // Stop if we have nothing to paste if (!state.componentToPaste) { return state @@ -444,7 +444,7 @@ export const getFrontendStore = () => { if (cut) { state.componentToPaste = null } else { - const randomizeIds = component => { + const randomizeIds = (component) => { if (!component) { return } @@ -497,7 +497,7 @@ export const getFrontendStore = () => { } await store.actions.preview.saveSelected() }, - updateCustomStyle: async style => { + updateCustomStyle: async (style) => { const selected = get(selectedComponent) selected._styles.custom = style await store.actions.preview.saveSelected() @@ -507,7 +507,7 @@ export const getFrontendStore = () => { selected._styles = { normal: {}, hover: {}, active: {} } await store.actions.preview.saveSelected() }, - updateTransition: async transition => { + updateTransition: async (transition) => { const selected = get(selectedComponent) if (transition == null || transition === "") { selected._transition = "" @@ -522,7 +522,7 @@ export const getFrontendStore = () => { return } component[name] = value - store.update(state => { + store.update((state) => { state.selectedComponentId = component._id return state }) diff --git a/packages/builder/src/builderStore/store/hosting.js b/packages/builder/src/builderStore/store/hosting.js index f180d4157a..d2112df862 100644 --- a/packages/builder/src/builderStore/store/hosting.js +++ b/packages/builder/src/builderStore/store/hosting.js @@ -17,18 +17,20 @@ export const getHostingStore = () => { api.get("/api/hosting/"), api.get("/api/hosting/urls"), ]) - const [info, urls] = await Promise.all(responses.map(resp => resp.json())) - store.update(state => { + const [info, urls] = await Promise.all( + responses.map((resp) => resp.json()) + ) + store.update((state) => { state.hostingInfo = info state.appUrl = urls.app return state }) return info }, - save: async hostingInfo => { + save: async (hostingInfo) => { const response = await api.post("/api/hosting", hostingInfo) const revision = (await response.json()).rev - store.update(state => { + store.update((state) => { state.hostingInfo = { ...hostingInfo, _rev: revision, @@ -38,10 +40,12 @@ export const getHostingStore = () => { }, fetchDeployedApps: async () => { let deployments = await (await get("/api/hosting/apps")).json() - store.update(state => { + store.update((state) => { state.deployedApps = deployments - state.deployedAppNames = Object.values(deployments).map(app => app.name) - state.deployedAppUrls = Object.values(deployments).map(app => app.url) + state.deployedAppNames = Object.values(deployments).map( + (app) => app.name + ) + state.deployedAppUrls = Object.values(deployments).map((app) => app.url) return state }) return deployments diff --git a/packages/builder/src/builderStore/store/localStorage.js b/packages/builder/src/builderStore/store/localStorage.js index aaf10460b6..a09031498e 100644 --- a/packages/builder/src/builderStore/store/localStorage.js +++ b/packages/builder/src/builderStore/store/localStorage.js @@ -12,13 +12,13 @@ export const localStorageStore = (localStorageKey, initialValue) => { }) // New store setter which updates the store and localstorage - const set = value => { + const set = (value) => { store.set(value) localStorage.setItem(localStorageKey, JSON.stringify(value)) } // New store updater which updates the store and localstorage - const update = updaterFn => set(updaterFn(get(store))) + const update = (updaterFn) => set(updaterFn(get(store))) // Hydrates the store from localstorage const hydrate = () => { diff --git a/packages/builder/src/builderStore/store/notifications.js b/packages/builder/src/builderStore/store/notifications.js index 85e708e92a..933e4a1d12 100644 --- a/packages/builder/src/builderStore/store/notifications.js +++ b/packages/builder/src/builderStore/store/notifications.js @@ -6,7 +6,7 @@ export const notificationStore = writable({ }) export function send(message, type = "default") { - notificationStore.update(state => { + notificationStore.update((state) => { state.notifications = [ ...state.notifications, { id: generate(), type, message }, @@ -16,8 +16,8 @@ export function send(message, type = "default") { } export const notifier = { - danger: msg => send(msg, "danger"), - warning: msg => send(msg, "warning"), - info: msg => send(msg, "info"), - success: msg => send(msg, "success"), + danger: (msg) => send(msg, "danger"), + warning: (msg) => send(msg, "warning"), + info: (msg) => send(msg, "info"), + success: (msg) => send(msg, "success"), } diff --git a/packages/builder/src/builderStore/store/screenTemplates/index.js b/packages/builder/src/builderStore/store/screenTemplates/index.js index 38ae434753..217426f489 100644 --- a/packages/builder/src/builderStore/store/screenTemplates/index.js +++ b/packages/builder/src/builderStore/store/screenTemplates/index.js @@ -3,7 +3,7 @@ import rowDetailScreen from "./rowDetailScreen" import rowListScreen from "./rowListScreen" import createFromScratchScreen from "./createFromScratchScreen" -const allTemplates = tables => [ +const allTemplates = (tables) => [ ...newRowScreen(tables), ...rowDetailScreen(tables), ...rowListScreen(tables), @@ -18,7 +18,7 @@ const createTemplateOverride = (frontendState, create) => () => { } export default (frontendState, tables) => { - const enrichTemplate = template => ({ + const enrichTemplate = (template) => ({ ...template, create: createTemplateOverride(frontendState, template.create), }) diff --git a/packages/builder/src/builderStore/store/screenTemplates/newRowScreen.js b/packages/builder/src/builderStore/store/screenTemplates/newRowScreen.js index 7788245d46..1599a07725 100644 --- a/packages/builder/src/builderStore/store/screenTemplates/newRowScreen.js +++ b/packages/builder/src/builderStore/store/screenTemplates/newRowScreen.js @@ -9,8 +9,8 @@ import { makeDatasourceFormComponents, } from "./utils/commonComponents" -export default function(tables) { - return tables.map(table => { +export default function (tables) { + return tables.map((table) => { return { name: `${table.name} - New`, create: () => createScreen(table), @@ -19,14 +19,14 @@ export default function(tables) { }) } -export const newRowUrl = table => sanitizeUrl(`/${table.name}/new/row`) +export const newRowUrl = (table) => sanitizeUrl(`/${table.name}/new/row`) export const NEW_ROW_TEMPLATE = "NEW_ROW_TEMPLATE" function generateTitleContainer(table, formId) { return makeTitleContainer("New Row").addChild(makeSaveButton(table, formId)) } -const createScreen = table => { +const createScreen = (table) => { const screen = new Screen() .component("@budibase/standard-components/container") .instanceName(`${table.name} - New`) @@ -52,7 +52,7 @@ const createScreen = table => { // Add all form fields from this schema to the field group const datasource = { type: "table", tableId: table._id } - makeDatasourceFormComponents(datasource).forEach(component => { + makeDatasourceFormComponents(datasource).forEach((component) => { fieldGroup.addChild(component) }) diff --git a/packages/builder/src/builderStore/store/screenTemplates/rowDetailScreen.js b/packages/builder/src/builderStore/store/screenTemplates/rowDetailScreen.js index 67a1d1c916..02889fa537 100644 --- a/packages/builder/src/builderStore/store/screenTemplates/rowDetailScreen.js +++ b/packages/builder/src/builderStore/store/screenTemplates/rowDetailScreen.js @@ -12,8 +12,8 @@ import { makeDatasourceFormComponents, } from "./utils/commonComponents" -export default function(tables) { - return tables.map(table => { +export default function (tables) { + return tables.map((table) => { return { name: `${table.name} - Detail`, create: () => createScreen(table), @@ -23,7 +23,7 @@ export default function(tables) { } export const ROW_DETAIL_TEMPLATE = "ROW_DETAIL_TEMPLATE" -export const rowDetailUrl = table => sanitizeUrl(`/${table.name}/:id`) +export const rowDetailUrl = (table) => sanitizeUrl(`/${table.name}/:id`) function generateTitleContainer(table, title, formId, repeaterId) { // have to override style for this, its missing margin @@ -77,12 +77,10 @@ function generateTitleContainer(table, title, formId, repeaterId) { }) .instanceName("Delete Button") - return makeTitleContainer(title) - .addChild(deleteButton) - .addChild(saveButton) + return makeTitleContainer(title).addChild(deleteButton).addChild(saveButton) } -const createScreen = table => { +const createScreen = (table) => { const provider = new Component("@budibase/standard-components/dataprovider") .instanceName(`Data Provider`) .customProps({ @@ -124,7 +122,7 @@ const createScreen = table => { // Add all form fields from this schema to the field group const datasource = { type: "table", tableId: table._id } - makeDatasourceFormComponents(datasource).forEach(component => { + makeDatasourceFormComponents(datasource).forEach((component) => { fieldGroup.addChild(component) }) diff --git a/packages/builder/src/builderStore/store/screenTemplates/rowListScreen.js b/packages/builder/src/builderStore/store/screenTemplates/rowListScreen.js index 4ebb35449f..390edfb143 100644 --- a/packages/builder/src/builderStore/store/screenTemplates/rowListScreen.js +++ b/packages/builder/src/builderStore/store/screenTemplates/rowListScreen.js @@ -4,8 +4,8 @@ import { Screen } from "./utils/Screen" import { Component } from "./utils/Component" import { makePropSafe } from "@budibase/string-templates" -export default function(tables) { - return tables.map(table => { +export default function (tables) { + return tables.map((table) => { return { name: `${table.name} - List`, create: () => createScreen(table), @@ -15,7 +15,7 @@ export default function(tables) { } export const ROW_LIST_TEMPLATE = "ROW_LIST_TEMPLATE" -export const rowListUrl = table => sanitizeUrl(`/${table.name}`) +export const rowListUrl = (table) => sanitizeUrl(`/${table.name}`) function generateTitleContainer(table) { const newButton = new Component("@budibase/standard-components/button") @@ -70,7 +70,7 @@ function generateTitleContainer(table) { .addChild(newButton) } -const createScreen = table => { +const createScreen = (table) => { const provider = new Component("@budibase/standard-components/dataprovider") .instanceName(`Data Provider`) .customProps({ diff --git a/packages/builder/src/builderStore/store/screenTemplates/utils/commonComponents.js b/packages/builder/src/builderStore/store/screenTemplates/utils/commonComponents.js index 19f950226c..18a777e509 100644 --- a/packages/builder/src/builderStore/store/screenTemplates/utils/commonComponents.js +++ b/packages/builder/src/builderStore/store/screenTemplates/utils/commonComponents.js @@ -178,7 +178,7 @@ export function makeDatasourceFormComponents(datasource) { const { schema } = getSchemaForDatasource(datasource, true) let components = [] let fields = Object.keys(schema || {}) - fields.forEach(field => { + fields.forEach((field) => { const fieldSchema = schema[field] // skip autocolumns if (fieldSchema.autocolumn) { diff --git a/packages/builder/src/builderStore/store/screenTemplates/utils/sanitizeUrl.js b/packages/builder/src/builderStore/store/screenTemplates/utils/sanitizeUrl.js index 96b7633e41..96e6b9df5d 100644 --- a/packages/builder/src/builderStore/store/screenTemplates/utils/sanitizeUrl.js +++ b/packages/builder/src/builderStore/store/screenTemplates/utils/sanitizeUrl.js @@ -1,7 +1,7 @@ -export default function(url) { +export default function (url) { return url .split("/") - .map(part => { + .map((part) => { // if parameter, then use as is if (part.startsWith(":")) return part return encodeURIComponent(part.replace(/ /g, "-")) diff --git a/packages/builder/src/builderStore/store/theme.js b/packages/builder/src/builderStore/store/theme.js index fd6b05df59..2c3ccd857c 100644 --- a/packages/builder/src/builderStore/store/theme.js +++ b/packages/builder/src/builderStore/store/theme.js @@ -9,14 +9,14 @@ export const getThemeStore = () => { const store = localStorageStore("bb-theme", initialValue) // Update theme class when store changes - store.subscribe(state => { + store.subscribe((state) => { // Handle any old local storage values - this can be removed after the update if (state.darkMode !== undefined) { store.set(initialValue) return } - state.options.forEach(option => { + state.options.forEach((option) => { themeElement.classList.toggle( `spectrum--${option}`, option === state.theme diff --git a/packages/builder/src/builderStore/storeUtils.js b/packages/builder/src/builderStore/storeUtils.js index 6d0f0beab0..2fd1dae8c1 100644 --- a/packages/builder/src/builderStore/storeUtils.js +++ b/packages/builder/src/builderStore/storeUtils.js @@ -2,14 +2,14 @@ * Recursively searches for a specific component ID */ export const findComponent = (rootComponent, id) => { - return searchComponentTree(rootComponent, comp => comp._id === id) + return searchComponentTree(rootComponent, (comp) => comp._id === id) } /** * Recursively searches for a specific component type */ export const findComponentType = (rootComponent, type) => { - return searchComponentTree(rootComponent, comp => comp._component === type) + return searchComponentTree(rootComponent, (comp) => comp._component === type) } /** @@ -68,7 +68,7 @@ export const findAllMatchingComponents = (rootComponent, selector) => { } let components = [] if (rootComponent._children) { - rootComponent._children.forEach(child => { + rootComponent._children.forEach((child) => { components = [ ...components, ...findAllMatchingComponents(child, selector), diff --git a/packages/builder/src/builderStore/uuid.js b/packages/builder/src/builderStore/uuid.js index 149da83c68..9cddf638bc 100644 --- a/packages/builder/src/builderStore/uuid.js +++ b/packages/builder/src/builderStore/uuid.js @@ -1,7 +1,7 @@ export function uuid() { // always want to make this start with a letter, as this makes it // easier to use with template string bindings in the client - return "cxxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, c => { + return "cxxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, (c) => { const r = (Math.random() * 16) | 0, v = c == "x" ? r : (r & 0x3) | 0x8 return v.toString(16) diff --git a/packages/builder/src/components/design/NavigationPanel/ComponentNavigationTree/dragDropStore.js b/packages/builder/src/components/design/NavigationPanel/ComponentNavigationTree/dragDropStore.js index 37c2f9867e..31ac3032f9 100644 --- a/packages/builder/src/components/design/NavigationPanel/ComponentNavigationTree/dragDropStore.js +++ b/packages/builder/src/components/design/NavigationPanel/ComponentNavigationTree/dragDropStore.js @@ -13,12 +13,12 @@ export const DropPosition = { INSIDE: "inside", } -export default function() { +export default function () { const store = writable({}) store.actions = { - dragstart: component => { - store.update(state => { + dragstart: (component) => { + store.update((state) => { state.dragged = component return state }) @@ -29,7 +29,7 @@ export default function() { canHaveChildrenButIsEmpty, mousePosition, }) => { - store.update(state => { + store.update((state) => { state.targetComponent = component // only allow dropping inside when container is empty // if container has children, drag over them @@ -65,7 +65,7 @@ export default function() { }) }, reset: () => { - store.update(state => { + store.update((state) => { state.dropPosition = "" state.targetComponent = null state.dragged = null @@ -85,7 +85,7 @@ export default function() { } // Stop if the target is a child of source const path = findComponentPath(state.dragged, state.targetComponent._id) - const ids = path.map(component => component._id) + const ids = path.map((component) => component._id) if (ids.includes(state.targetComponent._id)) { return } diff --git a/packages/builder/src/components/design/PropertiesPanel/PropertyControls/IconSelect/index.js b/packages/builder/src/components/design/PropertiesPanel/PropertyControls/IconSelect/index.js index 5f62d8970b..508be0f6c5 100644 --- a/packages/builder/src/components/design/PropertiesPanel/PropertyControls/IconSelect/index.js +++ b/packages/builder/src/components/design/PropertiesPanel/PropertyControls/IconSelect/index.js @@ -1 +1 @@ -export { default as IconSelect } from "./IconSelect.svelte" +export { default as IconSelect } from "./IconSelect.svelte" diff --git a/packages/builder/src/constants/completions.js b/packages/builder/src/constants/completions.js index 32de934324..7cee222046 100644 --- a/packages/builder/src/constants/completions.js +++ b/packages/builder/src/constants/completions.js @@ -3,7 +3,7 @@ import { getManifest } from "@budibase/string-templates" export function handlebarsCompletions() { const manifest = getManifest() - return Object.keys(manifest).flatMap(key => + return Object.keys(manifest).flatMap((key) => Object.entries(manifest[key]).map(([helperName, helperConfig]) => ({ text: helperName, path: helperName, diff --git a/packages/builder/src/helpers.js b/packages/builder/src/helpers.js index 89c7a0a6aa..8de210c159 100644 --- a/packages/builder/src/helpers.js +++ b/packages/builder/src/helpers.js @@ -1,6 +1,6 @@ import { last, flow } from "lodash/fp" -export const buildStyle = styles => { +export const buildStyle = (styles) => { let str = "" for (let s in styles) { if (styles[s]) { @@ -11,14 +11,15 @@ export const buildStyle = styles => { return str } -export const convertCamel = str => { - return str.replace(/[A-Z]/g, match => `-${match.toLowerCase()}`) +export const convertCamel = (str) => { + return str.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`) } export const pipe = (arg, funcs) => flow(funcs)(arg) -export const capitalise = s => s.substring(0, 1).toUpperCase() + s.substring(1) +export const capitalise = (s) => + s.substring(0, 1).toUpperCase() + s.substring(1) -export const get_name = s => (!s ? "" : last(s.split("/"))) +export const get_name = (s) => (!s ? "" : last(s.split("/"))) -export const get_capitalised_name = name => pipe(name, [get_name, capitalise]) +export const get_capitalised_name = (name) => pipe(name, [get_name, capitalise]) diff --git a/packages/builder/src/stores/backend/auth.js b/packages/builder/src/stores/backend/auth.js index 29dd6dcdd0..a2548a3deb 100644 --- a/packages/builder/src/stores/backend/auth.js +++ b/packages/builder/src/stores/backend/auth.js @@ -13,12 +13,12 @@ export function createAuthStore() { const { subscribe, set } = writable(null) checkAuth() - .then(user => set({ user })) + .then((user) => set({ user })) .catch(() => set({ user: null })) return { subscribe, - login: async creds => { + login: async (creds) => { const response = await api.post(`/api/admin/auth`, creds) const json = await response.json() if (response.status === 200) { @@ -36,7 +36,7 @@ export function createAuthStore() { await response.json() set({ user: null }) }, - createUser: async user => { + createUser: async (user) => { const response = await api.post(`/api/admin/users`, user) if (response.status !== 200) { throw "Unable to create user" diff --git a/packages/builder/src/stores/backend/datasources.js b/packages/builder/src/stores/backend/datasources.js index ff634c0185..563d3a98dd 100644 --- a/packages/builder/src/stores/backend/datasources.js +++ b/packages/builder/src/stores/backend/datasources.js @@ -21,19 +21,19 @@ export function createDatasourcesStore() { fetch: async () => { const response = await api.get(`/api/datasources`) const json = await response.json() - update(state => ({ ...state, list: json })) + update((state) => ({ ...state, list: json })) return json }, - select: async datasourceId => { - update(state => ({ ...state, selected: datasourceId })) - queries.update(state => ({ ...state, selected: null })) + select: async (datasourceId) => { + update((state) => ({ ...state, selected: datasourceId })) + queries.update((state) => ({ ...state, selected: null })) }, - save: async datasource => { + save: async (datasource) => { const response = await api.post("/api/datasources", datasource) const json = await response.json() - update(state => { - const currentIdx = state.list.findIndex(ds => ds._id === json._id) + update((state) => { + const currentIdx = state.list.findIndex((ds) => ds._id === json._id) const sources = state.list @@ -47,13 +47,13 @@ export function createDatasourcesStore() { }) return json }, - delete: async datasource => { + delete: async (datasource) => { const response = await api.delete( `/api/datasources/${datasource._id}/${datasource._rev}` ) - update(state => { + update((state) => { const sources = state.list.filter( - existing => existing._id !== datasource._id + (existing) => existing._id !== datasource._id ) return { list: sources, selected: null } }) diff --git a/packages/builder/src/stores/backend/permissions.js b/packages/builder/src/stores/backend/permissions.js index 9172210872..8d84e6d74b 100644 --- a/packages/builder/src/stores/backend/permissions.js +++ b/packages/builder/src/stores/backend/permissions.js @@ -6,7 +6,7 @@ export function createPermissionStore() { return { subscribe, - forResource: async resourceId => { + forResource: async (resourceId) => { const response = await api.get(`/api/permission/${resourceId}`) const json = await response.json() return json diff --git a/packages/builder/src/stores/backend/queries.js b/packages/builder/src/stores/backend/queries.js index 3870b7ec96..2eed72a635 100644 --- a/packages/builder/src/stores/backend/queries.js +++ b/packages/builder/src/stores/backend/queries.js @@ -17,13 +17,13 @@ export function createQueriesStore() { fetch: async () => { const response = await api.get(`/api/queries`) const json = await response.json() - update(state => ({ ...state, list: json })) + update((state) => ({ ...state, list: json })) return json }, save: async (datasourceId, query) => { const _integrations = get(integrations) const dataSource = get(datasources).list.filter( - ds => ds._id === datasourceId + (ds) => ds._id === datasourceId ) // check if readable attribute is found if (dataSource.length !== 0) { @@ -39,8 +39,10 @@ export function createQueriesStore() { throw new Error("Failed saving query.") } const json = await response.json() - update(state => { - const currentIdx = state.list.findIndex(query => query._id === json._id) + update((state) => { + const currentIdx = state.list.findIndex( + (query) => query._id === json._id + ) const queries = state.list @@ -53,16 +55,19 @@ export function createQueriesStore() { }) return json }, - select: query => { - update(state => ({ ...state, selected: query._id })) - datasources.update(state => ({ ...state, selected: query.datasourceId })) + select: (query) => { + update((state) => ({ ...state, selected: query._id })) + datasources.update((state) => ({ + ...state, + selected: query.datasourceId, + })) }, - delete: async query => { + delete: async (query) => { const response = await api.delete( `/api/queries/${query._id}/${query._rev}` ) - update(state => { - state.list = state.list.filter(existing => existing._id !== query._id) + update((state) => { + state.list = state.list.filter((existing) => existing._id !== query._id) if (state.selected === query._id) { state.selected = null } diff --git a/packages/builder/src/stores/backend/roles.js b/packages/builder/src/stores/backend/roles.js index 1a1a9c04c5..782036aefe 100644 --- a/packages/builder/src/stores/backend/roles.js +++ b/packages/builder/src/stores/backend/roles.js @@ -9,12 +9,12 @@ export function createRolesStore() { fetch: async () => { set(await getRoles()) }, - delete: async role => { + delete: async (role) => { const response = await api.delete(`/api/roles/${role._id}/${role._rev}`) - update(state => state.filter(existing => existing._id !== role._id)) + update((state) => state.filter((existing) => existing._id !== role._id)) return response }, - save: async role => { + save: async (role) => { const response = await api.post("/api/roles", role) set(await getRoles()) return response diff --git a/packages/builder/src/stores/backend/tables.js b/packages/builder/src/stores/backend/tables.js index faecf0d753..52e0a914c2 100644 --- a/packages/builder/src/stores/backend/tables.js +++ b/packages/builder/src/stores/backend/tables.js @@ -10,17 +10,17 @@ export function createTablesStore() { async function fetch() { const tablesResponse = await api.get(`/api/tables`) const tables = await tablesResponse.json() - update(state => ({ ...state, list: tables })) + update((state) => ({ ...state, list: tables })) } async function select(table) { if (!table) { - update(state => ({ + update((state) => ({ ...state, selected: {}, })) } else { - update(state => ({ + update((state) => ({ ...state, selected: table, draft: cloneDeep(table), @@ -31,7 +31,7 @@ export function createTablesStore() { async function save(table) { const updatedTable = cloneDeep(table) - const oldTable = get(store).list.filter(t => t._id === table._id)[0] + const oldTable = get(store).list.filter((t) => t._id === table._id)[0] const fieldNames = [] // update any renamed schema keys to reflect their names @@ -78,16 +78,16 @@ export function createTablesStore() { draft: {}, }) }, - delete: async table => { + delete: async (table) => { await api.delete(`/api/tables/${table._id}/${table._rev}`) - update(state => ({ + update((state) => ({ ...state, - list: state.list.filter(existing => existing._id !== table._id), + list: state.list.filter((existing) => existing._id !== table._id), selected: {}, })) }, saveField: ({ originalName, field, primaryDisplay = false, indexes }) => { - update(state => { + update((state) => { // delete the original if renaming // need to handle if the column had no name, empty string if (originalName || originalName === "") { @@ -115,8 +115,8 @@ export function createTablesStore() { return state }) }, - deleteField: field => { - update(state => { + deleteField: (field) => { + update((state) => { delete state.draft.schema[field.name] save(state.draft) return state diff --git a/packages/builder/src/stores/backend/views.js b/packages/builder/src/stores/backend/views.js index d6497bf871..b45f0aa4ed 100644 --- a/packages/builder/src/stores/backend/views.js +++ b/packages/builder/src/stores/backend/views.js @@ -10,17 +10,17 @@ export function createViewsStore() { return { subscribe, - select: async view => { - update(state => ({ + select: async (view) => { + update((state) => ({ ...state, selected: view, })) }, - delete: async view => { + delete: async (view) => { await api.delete(`/api/views/${view}`) await tables.fetch() }, - save: async view => { + save: async (view) => { const response = await api.post(`/api/views`, view) const json = await response.json() @@ -30,14 +30,14 @@ export function createViewsStore() { } const viewTable = get(tables).list.find( - table => table._id === view.tableId + (table) => table._id === view.tableId ) if (view.originalName) delete viewTable.views[view.originalName] viewTable.views[view.name] = viewMeta await tables.save(viewTable) - update(state => ({ ...state, selected: viewMeta })) + update((state) => ({ ...state, selected: viewMeta })) }, } } diff --git a/packages/cli/src/hosting/makeEnv.js b/packages/cli/src/hosting/makeEnv.js index 318a72def1..ee14fd5e31 100644 --- a/packages/cli/src/hosting/makeEnv.js +++ b/packages/cli/src/hosting/makeEnv.js @@ -61,7 +61,7 @@ module.exports.make = async (inputs = {}) => { ) } -module.exports.get = property => { +module.exports.get = (property) => { const props = fs.readFileSync(FILE_PATH, "utf8").split(property) if (props[0].charAt(0) === "=") { property = props[0] diff --git a/packages/cli/src/index.js b/packages/cli/src/index.js index 6693446b39..13e5386b59 100644 --- a/packages/cli/src/index.js +++ b/packages/cli/src/index.js @@ -17,6 +17,6 @@ async function init() { await program.parseAsync(process.argv) } -init().catch(err => { +init().catch((err) => { console.error(`Unexpected error - `, err) }) diff --git a/packages/cli/src/questions.js b/packages/cli/src/questions.js index ea0c412a60..d363c32790 100644 --- a/packages/cli/src/questions.js +++ b/packages/cli/src/questions.js @@ -1,6 +1,6 @@ const inquirer = require("inquirer") -exports.confirmation = async question => { +exports.confirmation = async (question) => { const config = { type: "confirm", message: question, @@ -27,7 +27,7 @@ exports.number = async (question, defaultNumber) => { type: "input", name: "number", message: question, - validate: value => { + validate: (value) => { let valid = !isNaN(parseFloat(value)) return valid || "Please enter a number" }, diff --git a/packages/cli/src/structures/Command.js b/packages/cli/src/structures/Command.js index a8d24566be..6d7da1a206 100644 --- a/packages/cli/src/structures/Command.js +++ b/packages/cli/src/structures/Command.js @@ -34,7 +34,7 @@ class Command { "--help", getSubHelpDescription(`Get help with ${this.command} options`) ) - command.action(async options => { + command.action(async (options) => { try { let executed = false for (let opt of thisCmd.opts) { diff --git a/packages/cli/src/utils.js b/packages/cli/src/utils.js index f61636389d..9da1eeeefa 100644 --- a/packages/cli/src/utils.js +++ b/packages/cli/src/utils.js @@ -21,23 +21,23 @@ exports.downloadFile = async (url, filePath) => { }) } -exports.getHelpDescription = string => { +exports.getHelpDescription = (string) => { return chalk.cyan(string) } -exports.getSubHelpDescription = string => { +exports.getSubHelpDescription = (string) => { return chalk.green(string) } -exports.error = error => { +exports.error = (error) => { return chalk.red(`Error - ${error}`) } -exports.success = success => { +exports.success = (success) => { return chalk.green(success) } -exports.info = info => { +exports.info = (info) => { return chalk.cyan(info) } @@ -45,7 +45,7 @@ exports.logErrorToFile = (file, error) => { fs.writeFileSync(path.resolve(`./${file}`), `Budibase Error\n${error}`) } -exports.parseEnv = env => { +exports.parseEnv = (env) => { const lines = env.toString().split("\n") let result = {} for (const line of lines) { diff --git a/packages/client/src/api/api.js b/packages/client/src/api/api.js index 8b2328c6a2..cd11f71ef4 100644 --- a/packages/client/src/api/api.js +++ b/packages/client/src/api/api.js @@ -7,7 +7,7 @@ let cache = {} /** * Handler for API errors. */ -const handleError = error => { +const handleError = (error) => { return { error } } @@ -61,7 +61,7 @@ const makeApiCall = async ({ method, url, body, json = true }) => { * Future invocation for this URL will return the cached result instead of * hitting the server again. */ -const makeCachedApiCall = async params => { +const makeCachedApiCall = async (params) => { const identifier = params.url if (!identifier) { return null @@ -76,7 +76,7 @@ const makeCachedApiCall = async params => { /** * Constructs an API call function for a particular HTTP method. */ -const requestApiCall = method => async params => { +const requestApiCall = (method) => async (params) => { const { url, cache = false } = params const fixedUrl = `/${url}`.replace("//", "/") const enrichedParams = { ...params, method, url: fixedUrl } diff --git a/packages/client/src/api/app.js b/packages/client/src/api/app.js index 61c23ef6a6..6f1f0679af 100644 --- a/packages/client/src/api/app.js +++ b/packages/client/src/api/app.js @@ -3,7 +3,7 @@ import API from "./api" /** * Fetches screen definition for an app. */ -export const fetchAppDefinition = async appId => { +export const fetchAppDefinition = async (appId) => { return await API.get({ url: `/api/applications/${appId}/definition`, }) diff --git a/packages/client/src/api/attachments.js b/packages/client/src/api/attachments.js index ff5c48c911..a03aa595f9 100644 --- a/packages/client/src/api/attachments.js +++ b/packages/client/src/api/attachments.js @@ -3,7 +3,7 @@ import API from "./api" /** * Uploads an attachment to the server. */ -export const uploadAttachment = async data => { +export const uploadAttachment = async (data) => { return await API.post({ url: "/api/attachments/upload", body: data, diff --git a/packages/client/src/api/datasources.js b/packages/client/src/api/datasources.js index 508e1e8db0..49d1132467 100644 --- a/packages/client/src/api/datasources.js +++ b/packages/client/src/api/datasources.js @@ -7,7 +7,7 @@ import { executeQuery } from "./queries" /** * Fetches all rows for a particular Budibase data source. */ -export const fetchDatasource = async dataSource => { +export const fetchDatasource = async (dataSource) => { if (!dataSource || !dataSource.type) { return [] } diff --git a/packages/client/src/api/rows.js b/packages/client/src/api/rows.js index 87cc9a9d37..b67c6318ae 100644 --- a/packages/client/src/api/rows.js +++ b/packages/client/src/api/rows.js @@ -18,7 +18,7 @@ export const fetchRow = async ({ tableId, rowId }) => { /** * Creates a row in a table. */ -export const saveRow = async row => { +export const saveRow = async (row) => { if (!row?.tableId) { return } @@ -39,7 +39,7 @@ export const saveRow = async row => { /** * Updates a row in a table. */ -export const updateRow = async row => { +export const updateRow = async (row) => { if (!row?.tableId || !row?._id) { return } @@ -115,15 +115,15 @@ export const enrichRows = async (rows, tableId) => { const schema = tableDefinition && tableDefinition.schema if (schema) { const keys = Object.keys(schema) - rows.forEach(row => { + rows.forEach((row) => { for (let key of keys) { const type = schema[key].type if (type === "link") { // Enrich row a string join of relationship fields row[`${key}_text`] = row[key] - ?.map(option => option?.primaryDisplay) - .filter(option => !!option) + ?.map((option) => option?.primaryDisplay) + .filter((option) => !!option) .join(", ") || "" } else if (type === "attachment") { // Enrich row with the first image URL for any attachment fields diff --git a/packages/client/src/api/tables.js b/packages/client/src/api/tables.js index 248e1516c2..86be3cd748 100644 --- a/packages/client/src/api/tables.js +++ b/packages/client/src/api/tables.js @@ -5,14 +5,14 @@ import { enrichRows } from "./rows" * Fetches a table definition. * Since definitions cannot change at runtime, the result is cached. */ -export const fetchTableDefinition = async tableId => { +export const fetchTableDefinition = async (tableId) => { return await API.get({ url: `/api/tables/${tableId}`, cache: true }) } /** * Fetches all rows from a table. */ -export const fetchTableData = async tableId => { +export const fetchTableData = async (tableId) => { const rows = await API.get({ url: `/api/${tableId}/rows` }) return await enrichRows(rows, tableId) } diff --git a/packages/client/src/store/builder.js b/packages/client/src/store/builder.js index 295bb6ccc9..9e1e87c800 100644 --- a/packages/client/src/store/builder.js +++ b/packages/client/src/store/builder.js @@ -12,7 +12,7 @@ const createBuilderStore = () => { } const store = writable(initialState) const actions = { - selectComponent: id => { + selectComponent: (id) => { if (id) { window.dispatchEvent( new CustomEvent("bb-select-component", { detail: id }) diff --git a/packages/client/src/store/context.js b/packages/client/src/store/context.js index e9d307d4f3..51d288fa38 100644 --- a/packages/client/src/store/context.js +++ b/packages/client/src/store/context.js @@ -1,9 +1,9 @@ import { writable, derived } from "svelte/store" -export const createContextStore = oldContext => { +export const createContextStore = (oldContext) => { const newContext = writable({}) const contexts = oldContext ? [oldContext, newContext] : [newContext] - const totalContext = derived(contexts, $contexts => { + const totalContext = derived(contexts, ($contexts) => { return $contexts.reduce((total, context) => ({ ...total, ...context }), {}) }) @@ -12,7 +12,7 @@ export const createContextStore = oldContext => { if (!providerId || data === undefined) { return } - newContext.update(state => { + newContext.update((state) => { state[providerId] = data // Keep track of the closest component ID so we can later hydrate a "data" prop. @@ -29,7 +29,7 @@ export const createContextStore = oldContext => { if (!providerId || !actionType) { return } - newContext.update(state => { + newContext.update((state) => { state[`${providerId}_${actionType}`] = callback return state }) diff --git a/packages/client/src/store/dataSource.js b/packages/client/src/store/dataSource.js index 2645c949a2..75d844a27e 100644 --- a/packages/client/src/store/dataSource.js +++ b/packages/client/src/store/dataSource.js @@ -40,8 +40,8 @@ export const createDataSourceStore = () => { // Store configs for each relevant dataSource ID if (dataSourceIds.length) { - store.update(state => { - dataSourceIds.forEach(id => { + store.update((state) => { + dataSourceIds.forEach((id) => { state.push({ dataSourceId: id, instanceId, @@ -55,22 +55,22 @@ export const createDataSourceStore = () => { // Removes all registered dataSource instances belonging to a particular // instance ID - const unregisterInstance = instanceId => { - store.update(state => { - return state.filter(instance => instance.instanceId !== instanceId) + const unregisterInstance = (instanceId) => { + store.update((state) => { + return state.filter((instance) => instance.instanceId !== instanceId) }) } // Invalidates a specific dataSource ID by refreshing all instances // which depend on data from that dataSource - const invalidateDataSource = dataSourceId => { - const relatedInstances = get(store).filter(instance => { + const invalidateDataSource = (dataSourceId) => { + const relatedInstances = get(store).filter((instance) => { return instance.dataSourceId === dataSourceId }) if (relatedInstances?.length) { notificationStore.blockNotifications(1000) } - relatedInstances?.forEach(instance => { + relatedInstances?.forEach((instance) => { instance.refresh() }) } diff --git a/packages/client/src/store/notification.js b/packages/client/src/store/notification.js index 3efd40a882..6e06760702 100644 --- a/packages/client/src/store/notification.js +++ b/packages/client/src/store/notification.js @@ -7,7 +7,7 @@ const createNotificationStore = () => { const _notifications = writable([], () => { return () => { // clear all the timers - timeoutIds.forEach(timeoutId => { + timeoutIds.forEach((timeoutId) => { clearTimeout(timeoutId) }) _notifications.set([]) @@ -25,11 +25,11 @@ const createNotificationStore = () => { return } let _id = id() - _notifications.update(state => { + _notifications.update((state) => { return [...state, { id: _id, type, message }] }) const timeoutId = setTimeout(() => { - _notifications.update(state => { + _notifications.update((state) => { return state.filter(({ id }) => id !== _id) }) }, NOTIFICATION_TIMEOUT) @@ -41,21 +41,16 @@ const createNotificationStore = () => { return { subscribe, send, - danger: msg => send(msg, "danger"), - warning: msg => send(msg, "warning"), - info: msg => send(msg, "info"), - success: msg => send(msg, "success"), + danger: (msg) => send(msg, "danger"), + warning: (msg) => send(msg, "warning"), + info: (msg) => send(msg, "info"), + success: (msg) => send(msg, "success"), blockNotifications, } } function id() { - return ( - "_" + - Math.random() - .toString(36) - .substr(2, 9) - ) + return "_" + Math.random().toString(36).substr(2, 9) } export const notificationStore = createNotificationStore() diff --git a/packages/client/src/store/routes.js b/packages/client/src/store/routes.js index aa86718ec0..71e61c9a58 100644 --- a/packages/client/src/store/routes.js +++ b/packages/client/src/store/routes.js @@ -14,7 +14,7 @@ const createRouteStore = () => { const fetchRoutes = async () => { const routeConfig = await API.fetchRoutes() let routes = [] - Object.values(routeConfig.routes).forEach(route => { + Object.values(routeConfig.routes).forEach((route) => { Object.entries(route.subpaths).forEach(([path, config]) => { routes.push({ path, @@ -28,21 +28,21 @@ const createRouteStore = () => { return a.path > b.path ? -1 : 1 }) - store.update(state => { + store.update((state) => { state.routes = routes state.routeSessionId = Math.random() return state }) } - const setRouteParams = routeParams => { - store.update(state => { + const setRouteParams = (routeParams) => { + store.update((state) => { state.routeParams = routeParams return state }) } - const setActiveRoute = route => { - store.update(state => { - state.activeRoute = state.routes.find(x => x.path === route) + const setActiveRoute = (route) => { + store.update((state) => { + state.activeRoute = state.routes.find((x) => x.path === route) return state }) } diff --git a/packages/client/src/store/screens.js b/packages/client/src/store/screens.js index 49927db9d7..7f21199acc 100644 --- a/packages/client/src/store/screens.js +++ b/packages/client/src/store/screens.js @@ -25,12 +25,12 @@ const createScreenStore = () => { activeScreen = screens[0] } else if ($routeStore.activeRoute) { activeScreen = screens.find( - screen => screen._id === $routeStore.activeRoute.screenId + (screen) => screen._id === $routeStore.activeRoute.screenId ) } if (activeScreen) { activeLayout = layouts.find( - layout => layout._id === activeScreen.layoutId + (layout) => layout._id === activeScreen.layoutId ) } } diff --git a/packages/client/src/utils/buttonActions.js b/packages/client/src/utils/buttonActions.js index 4d2865d586..0b988f0314 100644 --- a/packages/client/src/utils/buttonActions.js +++ b/packages/client/src/utils/buttonActions.js @@ -16,27 +16,27 @@ const saveRowHandler = async (action, context) => { } } -const deleteRowHandler = async action => { +const deleteRowHandler = async (action) => { const { tableId, revId, rowId } = action.parameters if (tableId && revId && rowId) { await deleteRow({ tableId, rowId, revId }) } } -const triggerAutomationHandler = async action => { +const triggerAutomationHandler = async (action) => { const { fields } = action.parameters if (fields) { await triggerAutomation(action.parameters.automationId, fields) } } -const navigationHandler = action => { +const navigationHandler = (action) => { if (action.parameters.url) { routeStore.actions.navigate(action.parameters.url) } } -const queryExecutionHandler = async action => { +const queryExecutionHandler = async (action) => { const { datasourceId, queryId, queryParams } = action.parameters await executeQuery({ datasourceId, @@ -68,7 +68,7 @@ const refreshDatasourceHandler = async (action, context) => { ) } -const loginHandler = async action => { +const loginHandler = async (action) => { const { email, password } = action.parameters await authStore.actions.logIn({ email, password }) } @@ -98,7 +98,7 @@ export const enrichButtonActions = (actions, context) => { if (get(builderStore).inBuilder) { return () => {} } - const handlers = actions.map(def => handlerMap[def["##eventHandlerType"]]) + const handlers = actions.map((def) => handlerMap[def["##eventHandlerType"]]) return async () => { for (let i = 0; i < handlers.length; i++) { try { diff --git a/packages/client/src/utils/hash.js b/packages/client/src/utils/hash.js index 2c42007e43..30c7913c20 100644 --- a/packages/client/src/utils/hash.js +++ b/packages/client/src/utils/hash.js @@ -1,4 +1,4 @@ -export const hashString = str => { +export const hashString = (str) => { if (!str) { return 0 } diff --git a/packages/client/src/utils/styleable.js b/packages/client/src/utils/styleable.js index 9a89f1d273..92707c7543 100644 --- a/packages/client/src/utils/styleable.js +++ b/packages/client/src/utils/styleable.js @@ -53,7 +53,7 @@ export const styleable = (node, styles = {}) => { } // Applies a style string to a DOM node - const applyStyles = styleString => { + const applyStyles = (styleString) => { node.style = addBuilderPreviewStyles(node, styleString, componentId) node.dataset.componentId = componentId } @@ -70,7 +70,7 @@ export const styleable = (node, styles = {}) => { // Handler to select a component in the builder when clicking it in the // builder preview - selectComponent = event => { + selectComponent = (event) => { builderStore.actions.selectComponent(componentId) event.preventDefault() event.stopPropagation() @@ -106,7 +106,7 @@ export const styleable = (node, styles = {}) => { return { // Clean up old listeners and apply new ones on update - update: newStyles => { + update: (newStyles) => { removeListeners() setupStyles(newStyles) }, diff --git a/packages/server/__mocks__/@elastic/elasticsearch.js b/packages/server/__mocks__/@elastic/elasticsearch.js index c6b2bad48a..9de0241f43 100644 --- a/packages/server/__mocks__/@elastic/elasticsearch.js +++ b/packages/server/__mocks__/@elastic/elasticsearch.js @@ -1,6 +1,6 @@ const elastic = {} -elastic.Client = function() { +elastic.Client = function () { this.index = jest.fn().mockResolvedValue({ body: [] }) this.search = jest.fn().mockResolvedValue({ body: { diff --git a/packages/server/__mocks__/arangojs.js b/packages/server/__mocks__/arangojs.js index 1a40529ca0..eff1d14172 100644 --- a/packages/server/__mocks__/arangojs.js +++ b/packages/server/__mocks__/arangojs.js @@ -1,6 +1,6 @@ const arangodb = {} -arangodb.Database = function() { +arangodb.Database = function () { this.query = jest.fn(() => ({ all: jest.fn(), })) diff --git a/packages/server/__mocks__/aws-sdk.js b/packages/server/__mocks__/aws-sdk.js index 503d098256..e76b1616e6 100644 --- a/packages/server/__mocks__/aws-sdk.js +++ b/packages/server/__mocks__/aws-sdk.js @@ -1,6 +1,6 @@ const aws = {} -const response = body => () => ({ promise: () => body }) +const response = (body) => () => ({ promise: () => body }) function DocumentClient() { this.put = jest.fn(response({})) diff --git a/packages/server/__mocks__/mongodb.js b/packages/server/__mocks__/mongodb.js index 160ca89ebe..c64e466a4a 100644 --- a/packages/server/__mocks__/mongodb.js +++ b/packages/server/__mocks__/mongodb.js @@ -1,6 +1,6 @@ const mongodb = {} -mongodb.MongoClient = function() { +mongodb.MongoClient = function () { this.connect = jest.fn() this.close = jest.fn() this.insertOne = jest.fn() diff --git a/packages/server/scripts/dev/manage.js b/packages/server/scripts/dev/manage.js index 4e170d1c63..0133bc8667 100644 --- a/packages/server/scripts/dev/manage.js +++ b/packages/server/scripts/dev/manage.js @@ -46,7 +46,7 @@ async function init() { SELF_HOSTED: 1, } let envFile = "" - Object.keys(envFileJson).forEach(key => { + Object.keys(envFileJson).forEach((key) => { envFile += `${key}=${envFileJson[key]}\n` }) fs.writeFileSync(envFilePath, envFile) @@ -78,7 +78,7 @@ const managementCommand = process.argv.slice(2)[0] if ( !managementCommand || - !Object.values(Commands).some(command => managementCommand === command) + !Object.values(Commands).some((command) => managementCommand === command) ) { throw new Error( "You must supply either an 'up', 'down' or 'nuke' commmand to manage the budibase development environment." @@ -104,7 +104,7 @@ command() .then(() => { console.log("Done! 🎉") }) - .catch(err => { + .catch((err) => { console.error( "Something went wrong while managing budibase dev environment:", err.message diff --git a/packages/server/scripts/exportAppTemplate.js b/packages/server/scripts/exportAppTemplate.js index 34988cda37..2673b9b284 100755 --- a/packages/server/scripts/exportAppTemplate.js +++ b/packages/server/scripts/exportAppTemplate.js @@ -25,7 +25,7 @@ yargs type: "string", }, }, - async args => { + async (args) => { if (!env.isDev()) { throw "Only works in dev" } diff --git a/packages/server/scripts/replicateApp.js b/packages/server/scripts/replicateApp.js index bbf44a7907..90f54087ce 100644 --- a/packages/server/scripts/replicateApp.js +++ b/packages/server/scripts/replicateApp.js @@ -14,7 +14,7 @@ console.log(`Replicating from ${appName} to ${remoteUrl}/${appName}`) const run = async () => { const allDbs = await CouchDB.allDbs() - const appDbNames = allDbs.filter(dbName => dbName.startsWith("inst_app")) + const appDbNames = allDbs.filter((dbName) => dbName.startsWith("inst_app")) let apps = [] for (let dbName of appDbNames) { const db = new CouchDB(dbName) @@ -22,12 +22,12 @@ const run = async () => { } apps = await Promise.all(apps) const app = apps.find( - a => a.name === appName || a.name.toLowerCase() === appName + (a) => a.name === appName || a.name.toLowerCase() === appName ) if (!app) { console.log( - `Could not find app... apps: ${apps.map(app => app.name).join(", ")}` + `Could not find app... apps: ${apps.map((app) => app.name).join(", ")}` ) return } @@ -37,10 +37,10 @@ const run = async () => { instanceDb.replicate .to(remoteDb) - .on("complete", function() { + .on("complete", function () { console.log("SUCCESS!") }) - .on("error", function(err) { + .on("error", function (err) { console.log(`FAILED: ${err}`) }) } diff --git a/packages/server/src/api/controllers/analytics.js b/packages/server/src/api/controllers/analytics.js index 76e5eb11f1..d6e1a9ce5b 100644 --- a/packages/server/src/api/controllers/analytics.js +++ b/packages/server/src/api/controllers/analytics.js @@ -1,6 +1,6 @@ const env = require("../../environment") -exports.isEnabled = async function(ctx) { +exports.isEnabled = async function (ctx) { ctx.body = { enabled: env.ENABLE_ANALYTICS === "true", } diff --git a/packages/server/src/api/controllers/apikeys.js b/packages/server/src/api/controllers/apikeys.js index 1c8caba1cb..55422ee603 100644 --- a/packages/server/src/api/controllers/apikeys.js +++ b/packages/server/src/api/controllers/apikeys.js @@ -1,6 +1,6 @@ const builderDB = require("../../db/builder") -exports.fetch = async function(ctx) { +exports.fetch = async function (ctx) { try { const mainDoc = await builderDB.getBuilderMainDoc() ctx.body = mainDoc.apiKeys ? mainDoc.apiKeys : {} @@ -10,7 +10,7 @@ exports.fetch = async function(ctx) { } } -exports.update = async function(ctx) { +exports.update = async function (ctx) { const key = ctx.params.key const value = ctx.request.body.value diff --git a/packages/server/src/api/controllers/application.js b/packages/server/src/api/controllers/application.js index beb1dedf47..4668a31675 100644 --- a/packages/server/src/api/controllers/application.js +++ b/packages/server/src/api/controllers/application.js @@ -43,7 +43,7 @@ async function getLayouts(db) { include_docs: true, }) ) - ).rows.map(row => row.doc) + ).rows.map((row) => row.doc) } async function getScreens(db) { @@ -53,7 +53,7 @@ async function getScreens(db) { include_docs: true, }) ) - ).rows.map(row => row.doc) + ).rows.map((row) => row.doc) } function getUserRoleId(ctx) { @@ -113,11 +113,11 @@ async function createInstance(template) { return { _id: appId } } -exports.fetch = async function(ctx) { +exports.fetch = async function (ctx) { ctx.body = await getAllApps() } -exports.fetchAppDefinition = async function(ctx) { +exports.fetchAppDefinition = async function (ctx) { const db = new CouchDB(ctx.params.appId) const layouts = await getLayouts(db) const userRoleId = getUserRoleId(ctx) @@ -133,7 +133,7 @@ exports.fetchAppDefinition = async function(ctx) { } } -exports.fetchAppPackage = async function(ctx) { +exports.fetchAppPackage = async function (ctx) { const db = new CouchDB(ctx.params.appId) const application = await db.get(ctx.params.appId) const [layouts, screens] = await Promise.all([getLayouts(db), getScreens(db)]) @@ -146,7 +146,7 @@ exports.fetchAppPackage = async function(ctx) { } } -exports.create = async function(ctx) { +exports.create = async function (ctx) { const { useTemplate, templateKey } = ctx.request.body const instanceConfig = { useTemplate, @@ -186,7 +186,7 @@ exports.create = async function(ctx) { ctx.message = `Application ${ctx.request.body.name} created successfully` } -exports.update = async function(ctx) { +exports.update = async function (ctx) { const url = await getAppUrlIfNotInUse(ctx) const db = new CouchDB(ctx.params.appId) const application = await db.get(ctx.params.appId) @@ -202,7 +202,7 @@ exports.update = async function(ctx) { ctx.body = response } -exports.delete = async function(ctx) { +exports.delete = async function (ctx) { const db = new CouchDB(ctx.params.appId) const app = await db.get(ctx.params.appId) const result = await db.destroy() diff --git a/packages/server/src/api/controllers/auth.js b/packages/server/src/api/controllers/auth.js index 2ac3d30e48..ed70254222 100644 --- a/packages/server/src/api/controllers/auth.js +++ b/packages/server/src/api/controllers/auth.js @@ -3,7 +3,7 @@ const { outputProcessing } = require("../../utilities/rowProcessor") const { InternalTables } = require("../../db/utils") const { getFullUser } = require("../../utilities/users") -exports.fetchSelf = async ctx => { +exports.fetchSelf = async (ctx) => { if (!ctx.user) { ctx.throw(403, "No user logged in") } diff --git a/packages/server/src/api/controllers/automation.js b/packages/server/src/api/controllers/automation.js index 0f210f633c..8238ffdb6b 100644 --- a/packages/server/src/api/controllers/automation.js +++ b/packages/server/src/api/controllers/automation.js @@ -93,7 +93,7 @@ async function checkForWebhooks({ appId, oldAuto, newAuto }) { return newAuto } -exports.create = async function(ctx) { +exports.create = async function (ctx) { const db = new CouchDB(ctx.appId) let automation = ctx.request.body automation.appId = ctx.appId @@ -124,7 +124,7 @@ exports.create = async function(ctx) { } } -exports.update = async function(ctx) { +exports.update = async function (ctx) { const db = new CouchDB(ctx.appId) let automation = ctx.request.body automation.appId = ctx.appId @@ -149,22 +149,22 @@ exports.update = async function(ctx) { } } -exports.fetch = async function(ctx) { +exports.fetch = async function (ctx) { const db = new CouchDB(ctx.appId) const response = await db.allDocs( getAutomationParams(null, { include_docs: true, }) ) - ctx.body = response.rows.map(row => row.doc) + ctx.body = response.rows.map((row) => row.doc) } -exports.find = async function(ctx) { +exports.find = async function (ctx) { const db = new CouchDB(ctx.appId) ctx.body = await db.get(ctx.params.id) } -exports.destroy = async function(ctx) { +exports.destroy = async function (ctx) { const db = new CouchDB(ctx.appId) const oldAutomation = await db.get(ctx.params.id) await checkForWebhooks({ @@ -174,19 +174,19 @@ exports.destroy = async function(ctx) { ctx.body = await db.remove(ctx.params.id, ctx.params.rev) } -exports.getActionList = async function(ctx) { +exports.getActionList = async function (ctx) { ctx.body = actions.DEFINITIONS } -exports.getTriggerList = async function(ctx) { +exports.getTriggerList = async function (ctx) { ctx.body = triggers.BUILTIN_DEFINITIONS } -exports.getLogicList = async function(ctx) { +exports.getLogicList = async function (ctx) { ctx.body = logic.BUILTIN_DEFINITIONS } -module.exports.getDefinitionList = async function(ctx) { +module.exports.getDefinitionList = async function (ctx) { ctx.body = { logic: logic.BUILTIN_DEFINITIONS, trigger: triggers.BUILTIN_DEFINITIONS, @@ -200,7 +200,7 @@ module.exports.getDefinitionList = async function(ctx) { * * *********************/ -exports.trigger = async function(ctx) { +exports.trigger = async function (ctx) { const db = new CouchDB(ctx.appId) let automation = await db.get(ctx.params.id) await triggers.externalTrigger(automation, { diff --git a/packages/server/src/api/controllers/backup.js b/packages/server/src/api/controllers/backup.js index 02be10bbec..0be19eb7bd 100644 --- a/packages/server/src/api/controllers/backup.js +++ b/packages/server/src/api/controllers/backup.js @@ -1,6 +1,6 @@ const { performBackup } = require("../../utilities/fileSystem") -exports.exportAppDump = async function(ctx) { +exports.exportAppDump = async function (ctx) { const { appId } = ctx.query const appname = decodeURI(ctx.query.appname) const backupIdentifier = `${appname}Backup${new Date().getTime()}.txt` diff --git a/packages/server/src/api/controllers/component.js b/packages/server/src/api/controllers/component.js index a9b88a5bff..2c9440058e 100644 --- a/packages/server/src/api/controllers/component.js +++ b/packages/server/src/api/controllers/component.js @@ -1,13 +1,13 @@ const CouchDB = require("../../db") const { getComponentLibraryManifest } = require("../../utilities/fileSystem") -exports.fetchAppComponentDefinitions = async function(ctx) { +exports.fetchAppComponentDefinitions = async function (ctx) { const appId = ctx.params.appId || ctx.appId const db = new CouchDB(appId) const app = await db.get(appId) let componentManifests = await Promise.all( - app.componentLibraries.map(async library => { + app.componentLibraries.map(async (library) => { let manifest = await getComponentLibraryManifest(appId, library) return { diff --git a/packages/server/src/api/controllers/datasource.js b/packages/server/src/api/controllers/datasource.js index b5a207dbbe..bd8497c4a4 100644 --- a/packages/server/src/api/controllers/datasource.js +++ b/packages/server/src/api/controllers/datasource.js @@ -5,7 +5,7 @@ const { getQueryParams, } = require("../../db/utils") -exports.fetch = async function(ctx) { +exports.fetch = async function (ctx) { const database = new CouchDB(ctx.appId) ctx.body = ( await database.allDocs( @@ -13,10 +13,10 @@ exports.fetch = async function(ctx) { include_docs: true, }) ) - ).rows.map(row => row.doc) + ).rows.map((row) => row.doc) } -exports.save = async function(ctx) { +exports.save = async function (ctx) { const db = new CouchDB(ctx.appId) const datasource = { @@ -33,12 +33,12 @@ exports.save = async function(ctx) { ctx.body = datasource } -exports.destroy = async function(ctx) { +exports.destroy = async function (ctx) { const db = new CouchDB(ctx.appId) // Delete all queries for the datasource const rows = await db.allDocs(getQueryParams(ctx.params.datasourceId, null)) - await db.bulkDocs(rows.rows.map(row => ({ ...row.doc, _deleted: true }))) + await db.bulkDocs(rows.rows.map((row) => ({ ...row.doc, _deleted: true }))) // delete the datasource await db.remove(ctx.params.datasourceId, ctx.params.revId) @@ -47,7 +47,7 @@ exports.destroy = async function(ctx) { ctx.status = 200 } -exports.find = async function(ctx) { +exports.find = async function (ctx) { const database = new CouchDB(ctx.appId) ctx.body = await database.get(ctx.params.datasourceId) } diff --git a/packages/server/src/api/controllers/deploy/awsDeploy.js b/packages/server/src/api/controllers/deploy/awsDeploy.js index 2d34bc1b04..c9fc1e9e52 100644 --- a/packages/server/src/api/controllers/deploy/awsDeploy.js +++ b/packages/server/src/api/controllers/deploy/awsDeploy.js @@ -13,7 +13,7 @@ const { * Links to the "check-api-key" lambda. * @param {object} deployment - information about the active deployment, including the appId and quota. */ -exports.preDeployment = async function(deployment) { +exports.preDeployment = async function (deployment) { const json = await fetchCredentials(env.DEPLOYMENT_CREDENTIALS_URL, { apiKey: env.BUDIBASE_API_KEY, appId: deployment.getAppId(), @@ -39,7 +39,7 @@ exports.preDeployment = async function(deployment) { * @param {object} deployment information about the active deployment, including the quota info. * @returns {Promise} The usage has been updated against the user API key. */ -exports.postDeployment = async function(deployment) { +exports.postDeployment = async function (deployment) { const DEPLOYMENT_SUCCESS_URL = env.DEPLOYMENT_CREDENTIALS_URL + "deploy/success" @@ -62,14 +62,14 @@ exports.postDeployment = async function(deployment) { return await response.json() } -exports.deploy = async function(deployment) { +exports.deploy = async function (deployment) { const appId = deployment.getAppId() const { bucket, accountId } = deployment.getVerification() const metadata = { accountId } await deployToObjectStore(appId, bucket, metadata) } -exports.replicateDb = async function(deployment) { +exports.replicateDb = async function (deployment) { const appId = deployment.getAppId() const verification = deployment.getVerification() return performReplication( diff --git a/packages/server/src/api/controllers/deploy/index.js b/packages/server/src/api/controllers/deploy/index.js index 490fb3c72e..1152b56db8 100644 --- a/packages/server/src/api/controllers/deploy/index.js +++ b/packages/server/src/api/controllers/deploy/index.js @@ -91,7 +91,7 @@ async function deployApp(deployment) { } } -exports.fetchDeployments = async function(ctx) { +exports.fetchDeployments = async function (ctx) { try { const db = new PouchDB(ctx.appId) const deploymentDoc = await db.get("_local/deployments") @@ -108,7 +108,7 @@ exports.fetchDeployments = async function(ctx) { } } -exports.deploymentProgress = async function(ctx) { +exports.deploymentProgress = async function (ctx) { try { const db = new PouchDB(ctx.appId) const deploymentDoc = await db.get("_local/deployments") @@ -121,7 +121,7 @@ exports.deploymentProgress = async function(ctx) { } } -exports.deployApp = async function(ctx) { +exports.deployApp = async function (ctx) { // start by checking whether to deploy local or to cloud const hostingInfo = await getHostingInfo() deploymentService = diff --git a/packages/server/src/api/controllers/deploy/quota.js b/packages/server/src/api/controllers/deploy/quota.js index 5e8880c7a9..368fce0bd3 100644 --- a/packages/server/src/api/controllers/deploy/quota.js +++ b/packages/server/src/api/controllers/deploy/quota.js @@ -6,7 +6,7 @@ const { ViewNames, } = require("../../../db/utils") -exports.getAppQuota = async function(appId) { +exports.getAppQuota = async function (appId) { const db = new PouchDB(appId) const rows = await db.allDocs({ diff --git a/packages/server/src/api/controllers/deploy/selfDeploy.js b/packages/server/src/api/controllers/deploy/selfDeploy.js index 444e7cd873..6a1849d4be 100644 --- a/packages/server/src/api/controllers/deploy/selfDeploy.js +++ b/packages/server/src/api/controllers/deploy/selfDeploy.js @@ -10,7 +10,7 @@ const { getSelfHostKey, } = require("../../../utilities/builder/hosting") -exports.preDeployment = async function() { +exports.preDeployment = async function () { const url = `${await getWorkerUrl()}/api/deploy` try { const json = await fetchCredentials(url, { @@ -37,11 +37,11 @@ exports.preDeployment = async function() { } } -exports.postDeployment = async function() { +exports.postDeployment = async function () { // we don't actively need to do anything after deployment in self hosting } -exports.deploy = async function(deployment) { +exports.deploy = async function (deployment) { const appId = deployment.getAppId() const verification = deployment.getVerification() // no metadata, aws has account ID in metadata @@ -49,7 +49,7 @@ exports.deploy = async function(deployment) { await deployToObjectStore(appId, verification.bucket, metadata) } -exports.replicateDb = async function(deployment) { +exports.replicateDb = async function (deployment) { const appId = deployment.getAppId() const verification = deployment.getVerification() return performReplication( diff --git a/packages/server/src/api/controllers/deploy/utils.js b/packages/server/src/api/controllers/deploy/utils.js index c5ac0641aa..2b5d0af2ed 100644 --- a/packages/server/src/api/controllers/deploy/utils.js +++ b/packages/server/src/api/controllers/deploy/utils.js @@ -22,7 +22,7 @@ function walkDir(dirPath, callback) { } } -exports.fetchCredentials = async function(url, body) { +exports.fetchCredentials = async function (url, body) { const response = await fetch(url, { method: "POST", body: JSON.stringify(body), @@ -43,7 +43,7 @@ exports.fetchCredentials = async function(url, body) { return json } -exports.prepareUpload = async function({ s3Key, bucket, metadata, file }) { +exports.prepareUpload = async function ({ s3Key, bucket, metadata, file }) { const response = await upload({ bucket, metadata, @@ -62,13 +62,13 @@ exports.prepareUpload = async function({ s3Key, bucket, metadata, file }) { } } -exports.deployToObjectStore = async function(appId, bucket, metadata) { +exports.deployToObjectStore = async function (appId, bucket, metadata) { const appAssetsPath = join(budibaseAppsDir(), appId, "public") let uploads = [] // Upload HTML, CSS and JS for each page of the web app - walkDir(appAssetsPath, function(filePath) { + walkDir(appAssetsPath, function (filePath) { const filePathParts = filePath.split("/") const appAssetUpload = exports.prepareUpload({ bucket, @@ -122,7 +122,7 @@ exports.performReplication = (appId, session, dbUrl) => { const local = new PouchDB(appId) const remote = new CouchDB(`${dbUrl}/${appId}`, { - fetch: function(url, opts) { + fetch: function (url, opts) { opts.headers.set("Cookie", `${session};`) return CouchDB.fetch(url, opts) }, @@ -131,6 +131,6 @@ exports.performReplication = (appId, session, dbUrl) => { const replication = local.sync(remote) replication.on("complete", () => resolve()) - replication.on("error", err => reject(err)) + replication.on("error", (err) => reject(err)) }) } diff --git a/packages/server/src/api/controllers/dev.js b/packages/server/src/api/controllers/dev.js index 003f82faa8..2e2a6d57f8 100644 --- a/packages/server/src/api/controllers/dev.js +++ b/packages/server/src/api/controllers/dev.js @@ -21,14 +21,14 @@ async function redirect(ctx, method) { ctx.cookies } -exports.redirectGet = async ctx => { +exports.redirectGet = async (ctx) => { await redirect(ctx, "GET") } -exports.redirectPost = async ctx => { +exports.redirectPost = async (ctx) => { await redirect(ctx, "POST") } -exports.redirectDelete = async ctx => { +exports.redirectDelete = async (ctx) => { await redirect(ctx, "DELETE") } diff --git a/packages/server/src/api/controllers/hosting.js b/packages/server/src/api/controllers/hosting.js index 8b7b31e00a..1720378fa2 100644 --- a/packages/server/src/api/controllers/hosting.js +++ b/packages/server/src/api/controllers/hosting.js @@ -7,13 +7,13 @@ const { } = require("../../utilities/builder/hosting") const { StaticDatabases } = require("../../db/utils") -exports.fetchInfo = async ctx => { +exports.fetchInfo = async (ctx) => { ctx.body = { types: Object.values(HostingTypes), } } -exports.save = async ctx => { +exports.save = async (ctx) => { const db = new CouchDB(StaticDatabases.BUILDER_HOSTING.name) const { type } = ctx.request.body if (type === HostingTypes.CLOUD && ctx.request.body._rev) { @@ -29,16 +29,16 @@ exports.save = async ctx => { } } -exports.fetch = async ctx => { +exports.fetch = async (ctx) => { ctx.body = await getHostingInfo() } -exports.fetchUrls = async ctx => { +exports.fetchUrls = async (ctx) => { ctx.body = { app: await getAppUrl(ctx.appId), } } -exports.getDeployedApps = async ctx => { +exports.getDeployedApps = async (ctx) => { ctx.body = await getDeployedApps(ctx) } diff --git a/packages/server/src/api/controllers/integration.js b/packages/server/src/api/controllers/integration.js index d8c726c8f3..f1aafe7e45 100644 --- a/packages/server/src/api/controllers/integration.js +++ b/packages/server/src/api/controllers/integration.js @@ -1,12 +1,12 @@ const { definitions } = require("../../integrations") -exports.fetch = async function(ctx) { +exports.fetch = async function (ctx) { // TODO: fetch these from a github repo etc ctx.status = 200 ctx.body = definitions } -exports.find = async function(ctx) { +exports.find = async function (ctx) { ctx.status = 200 ctx.body = definitions[ctx.params.type] } diff --git a/packages/server/src/api/controllers/layout.js b/packages/server/src/api/controllers/layout.js index 86c324d178..f745761d42 100644 --- a/packages/server/src/api/controllers/layout.js +++ b/packages/server/src/api/controllers/layout.js @@ -2,7 +2,7 @@ const { EMPTY_LAYOUT } = require("../../constants/layouts") const CouchDB = require("../../db") const { generateLayoutID, getScreenParams } = require("../../db/utils") -exports.save = async function(ctx) { +exports.save = async function (ctx) { const db = new CouchDB(ctx.appId) let layout = ctx.request.body @@ -21,7 +21,7 @@ exports.save = async function(ctx) { ctx.status = 200 } -exports.destroy = async function(ctx) { +exports.destroy = async function (ctx) { const db = new CouchDB(ctx.appId) const layoutId = ctx.params.layoutId, layoutRev = ctx.params.layoutRev @@ -32,7 +32,7 @@ exports.destroy = async function(ctx) { include_docs: true, }) ) - ).rows.map(element => element.doc.layoutId) + ).rows.map((element) => element.doc.layoutId) if (layoutsUsedByScreens.includes(layoutId)) { ctx.throw(400, "Cannot delete a layout that's being used by a screen") } diff --git a/packages/server/src/api/controllers/permission.js b/packages/server/src/api/controllers/permission.js index 56c9d3f8c6..ffce2e8d97 100644 --- a/packages/server/src/api/controllers/permission.js +++ b/packages/server/src/api/controllers/permission.js @@ -47,7 +47,7 @@ async function getAllDBRoles(db) { include_docs: true, }) ) - return body.rows.map(row => row.doc) + return body.rows.map((row) => row.doc) } async function updatePermissionOnRole( @@ -63,7 +63,7 @@ async function updatePermissionOnRole( const docUpdates = [] // the permission is for a built in, make sure it exists - if (isABuiltin && !dbRoles.some(role => role._id === dbRoleId)) { + if (isABuiltin && !dbRoles.some((role) => role._id === dbRoleId)) { const builtin = getBuiltinRoles()[roleId] builtin._id = getDBRoleID(builtin._id) dbRoles.push(builtin) @@ -101,23 +101,23 @@ async function updatePermissionOnRole( } const response = await db.bulkDocs(docUpdates) - return response.map(resp => { + return response.map((resp) => { resp._id = getExternalRoleID(resp.id) delete resp.id return resp }) } -exports.fetchBuiltin = function(ctx) { +exports.fetchBuiltin = function (ctx) { ctx.body = Object.values(getBuiltinPermissions()) } -exports.fetchLevels = function(ctx) { +exports.fetchLevels = function (ctx) { // for now only provide the read/write perms externally ctx.body = SUPPORTED_LEVELS } -exports.fetch = async function(ctx) { +exports.fetch = async function (ctx) { const db = new CouchDB(ctx.appId) const roles = await getAllDBRoles(db) let permissions = {} @@ -144,7 +144,7 @@ exports.fetch = async function(ctx) { ctx.body = finalPermissions } -exports.getResourcePerms = async function(ctx) { +exports.getResourcePerms = async function (ctx) { const resourceId = ctx.params.resourceId const db = new CouchDB(ctx.appId) const body = await db.allDocs( @@ -152,7 +152,7 @@ exports.getResourcePerms = async function(ctx) { include_docs: true, }) ) - const roles = body.rows.map(row => row.doc) + const roles = body.rows.map((row) => row.doc) let permissions = {} for (let level of SUPPORTED_LEVELS) { // update the various roleIds in the resource permissions @@ -169,7 +169,7 @@ exports.getResourcePerms = async function(ctx) { ctx.body = Object.assign(getBasePermissions(resourceId), permissions) } -exports.addPermission = async function(ctx) { +exports.addPermission = async function (ctx) { ctx.body = await updatePermissionOnRole( ctx.appId, ctx.params, @@ -177,7 +177,7 @@ exports.addPermission = async function(ctx) { ) } -exports.removePermission = async function(ctx) { +exports.removePermission = async function (ctx) { ctx.body = await updatePermissionOnRole( ctx.appId, ctx.params, diff --git a/packages/server/src/api/controllers/query.js b/packages/server/src/api/controllers/query.js index ddf88e925f..1f3e7370d8 100644 --- a/packages/server/src/api/controllers/query.js +++ b/packages/server/src/api/controllers/query.js @@ -27,7 +27,7 @@ function formatResponse(resp) { return resp } -exports.fetch = async function(ctx) { +exports.fetch = async function (ctx) { const db = new CouchDB(ctx.appId) const body = await db.allDocs( @@ -35,10 +35,10 @@ exports.fetch = async function(ctx) { include_docs: true, }) ) - ctx.body = enrichQueries(body.rows.map(row => row.doc)) + ctx.body = enrichQueries(body.rows.map((row) => row.doc)) } -exports.save = async function(ctx) { +exports.save = async function (ctx) { const db = new CouchDB(ctx.appId) const query = ctx.request.body @@ -89,7 +89,7 @@ async function enrichQueryFields(fields, parameters) { return enrichedQuery } -exports.find = async function(ctx) { +exports.find = async function (ctx) { const db = new CouchDB(ctx.appId) const query = enrichQueries(await db.get(ctx.params.queryId)) // remove properties that could be dangerous in real app @@ -101,7 +101,7 @@ exports.find = async function(ctx) { ctx.body = query } -exports.preview = async function(ctx) { +exports.preview = async function (ctx) { const db = new CouchDB(ctx.appId) const datasource = await db.get(ctx.request.body.datasourceId) @@ -129,7 +129,7 @@ exports.preview = async function(ctx) { } } -exports.execute = async function(ctx) { +exports.execute = async function (ctx) { const db = new CouchDB(ctx.appId) const query = await db.get(ctx.params.queryId) @@ -152,7 +152,7 @@ exports.execute = async function(ctx) { ) } -exports.destroy = async function(ctx) { +exports.destroy = async function (ctx) { const db = new CouchDB(ctx.appId) await db.remove(ctx.params.queryId, ctx.params.revId) ctx.message = `Query deleted.` diff --git a/packages/server/src/api/controllers/role.js b/packages/server/src/api/controllers/role.js index 42213b010d..19174cac35 100644 --- a/packages/server/src/api/controllers/role.js +++ b/packages/server/src/api/controllers/role.js @@ -50,27 +50,27 @@ async function updateRolesOnUserTable(db, roleId, updateOption) { } } -exports.fetch = async function(ctx) { +exports.fetch = async function (ctx) { const db = new CouchDB(ctx.appId) const body = await db.allDocs( getRoleParams(null, { include_docs: true, }) ) - let roles = body.rows.map(row => row.doc) + let roles = body.rows.map((row) => row.doc) const builtinRoles = getBuiltinRoles() // need to combine builtin with any DB record of them (for sake of permissions) for (let builtinRoleId of EXTERNAL_BUILTIN_ROLE_IDS) { const builtinRole = builtinRoles[builtinRoleId] const dbBuiltin = roles.filter( - dbRole => getExternalRoleID(dbRole._id) === builtinRoleId + (dbRole) => getExternalRoleID(dbRole._id) === builtinRoleId )[0] if (dbBuiltin == null) { roles.push(builtinRole) } else { // remove role and all back after combining with the builtin - roles = roles.filter(role => role._id !== dbBuiltin._id) + roles = roles.filter((role) => role._id !== dbBuiltin._id) dbBuiltin._id = getExternalRoleID(dbBuiltin._id) roles.push(Object.assign(builtinRole, dbBuiltin)) } @@ -78,11 +78,11 @@ exports.fetch = async function(ctx) { ctx.body = roles } -exports.find = async function(ctx) { +exports.find = async function (ctx) { ctx.body = await getRole(ctx.appId, ctx.params.roleId) } -exports.save = async function(ctx) { +exports.save = async function (ctx) { const db = new CouchDB(ctx.appId) let { _id, name, inherits, permissionId } = ctx.request.body if (!_id) { @@ -103,7 +103,7 @@ exports.save = async function(ctx) { ctx.message = `Role '${role.name}' created successfully.` } -exports.destroy = async function(ctx) { +exports.destroy = async function (ctx) { const db = new CouchDB(ctx.appId) const roleId = ctx.params.roleId if (isBuiltin(roleId)) { @@ -116,8 +116,8 @@ exports.destroy = async function(ctx) { include_docs: true, }) ) - ).rows.map(row => row.doc) - const usersWithRole = users.filter(user => user.roleId === roleId) + ).rows.map((row) => row.doc) + const usersWithRole = users.filter((user) => user.roleId === roleId) if (usersWithRole.length !== 0) { ctx.throw(400, "Cannot delete role when it is in use.") } diff --git a/packages/server/src/api/controllers/routing.js b/packages/server/src/api/controllers/routing.js index ab1489145b..502b78f107 100644 --- a/packages/server/src/api/controllers/routing.js +++ b/packages/server/src/api/controllers/routing.js @@ -10,7 +10,7 @@ function Routing() { this.json = {} } -Routing.prototype.getTopLevel = function(fullpath) { +Routing.prototype.getTopLevel = function (fullpath) { if (fullpath.charAt(0) !== URL_SEPARATOR) { fullpath = URL_SEPARATOR + fullpath } @@ -18,7 +18,7 @@ Routing.prototype.getTopLevel = function(fullpath) { return URL_SEPARATOR + fullpath.split(URL_SEPARATOR)[1] } -Routing.prototype.getScreensProp = function(fullpath) { +Routing.prototype.getScreensProp = function (fullpath) { const topLevel = this.getTopLevel(fullpath) if (!this.json[topLevel]) { this.json[topLevel] = { @@ -33,7 +33,7 @@ Routing.prototype.getScreensProp = function(fullpath) { return this.json[topLevel].subpaths[fullpath].screens } -Routing.prototype.addScreenId = function(fullpath, roleId, screenId) { +Routing.prototype.addScreenId = function (fullpath, roleId, screenId) { this.getScreensProp(fullpath)[roleId] = screenId } @@ -56,11 +56,11 @@ async function getRoutingStructure(appId) { return { routes: routing.json } } -exports.fetch = async ctx => { +exports.fetch = async (ctx) => { ctx.body = await getRoutingStructure(ctx.appId) } -exports.clientFetch = async ctx => { +exports.clientFetch = async (ctx) => { const routing = await getRoutingStructure(ctx.appId) let roleId = ctx.user.role._id // builder is a special case, always return the full routing structure diff --git a/packages/server/src/api/controllers/row.js b/packages/server/src/api/controllers/row.js index 48766129b2..f085ca91db 100644 --- a/packages/server/src/api/controllers/row.js +++ b/packages/server/src/api/controllers/row.js @@ -27,11 +27,11 @@ const CALCULATION_TYPES = { } validateJs.extend(validateJs.validators.datetime, { - parse: function(value) { + parse: function (value) { return new Date(value).getTime() }, // Input is a unix timestamp - format: function(value) { + format: function (value) { return new Date(value).toISOString() }, }) @@ -54,7 +54,7 @@ async function findRow(ctx, db, tableId, rowId) { return row } -exports.patch = async function(ctx) { +exports.patch = async function (ctx) { const appId = ctx.appId const db = new CouchDB(appId) let dbRow = await db.get(ctx.params.rowId) @@ -115,7 +115,7 @@ exports.patch = async function(ctx) { ctx.message = `${table.name} updated successfully.` } -exports.save = async function(ctx) { +exports.save = async function (ctx) { const appId = ctx.appId const db = new CouchDB(appId) let inputs = ctx.request.body @@ -189,7 +189,7 @@ exports.save = async function(ctx) { ctx.message = `${table.name} saved successfully` } -exports.fetchView = async function(ctx) { +exports.fetchView = async function (ctx) { const appId = ctx.appId const viewName = ctx.params.viewName @@ -213,7 +213,7 @@ exports.fetchView = async function(ctx) { }) if (!calculation) { - response.rows = response.rows.map(row => row.doc) + response.rows = response.rows.map((row) => row.doc) let table try { table = await db.get(viewInfo.meta.tableId) @@ -227,7 +227,7 @@ exports.fetchView = async function(ctx) { } if (calculation === CALCULATION_TYPES.STATS) { - response.rows = response.rows.map(row => ({ + response.rows = response.rows.map((row) => ({ group: row.key, field, ...row.value, @@ -240,7 +240,7 @@ exports.fetchView = async function(ctx) { calculation === CALCULATION_TYPES.COUNT || calculation === CALCULATION_TYPES.SUM ) { - ctx.body = response.rows.map(row => ({ + ctx.body = response.rows.map((row) => ({ group: row.key, field, value: row.value, @@ -248,7 +248,7 @@ exports.fetchView = async function(ctx) { } } -exports.search = async function(ctx) { +exports.search = async function (ctx) { const appId = ctx.appId const db = new CouchDB(appId) const { @@ -287,7 +287,7 @@ exports.search = async function(ctx) { } } -exports.fetchTableRows = async function(ctx) { +exports.fetchTableRows = async function (ctx) { const appId = ctx.appId const db = new CouchDB(appId) @@ -303,12 +303,12 @@ exports.fetchTableRows = async function(ctx) { include_docs: true, }) ) - rows = response.rows.map(row => row.doc) + rows = response.rows.map((row) => row.doc) } ctx.body = await outputProcessing(appId, table, rows) } -exports.find = async function(ctx) { +exports.find = async function (ctx) { const appId = ctx.appId const db = new CouchDB(appId) try { @@ -320,7 +320,7 @@ exports.find = async function(ctx) { } } -exports.destroy = async function(ctx) { +exports.destroy = async function (ctx) { const appId = ctx.appId const db = new CouchDB(appId) const row = await db.get(ctx.params.rowId) @@ -349,7 +349,7 @@ exports.destroy = async function(ctx) { ctx.eventEmitter && ctx.eventEmitter.emitRow(`row:delete`, appId, row) } -exports.validate = async function(ctx) { +exports.validate = async function (ctx) { const errors = await validate({ appId: ctx.appId, tableId: ctx.params.tableId, @@ -380,7 +380,7 @@ async function validate({ appId, tableId, row, table }) { return { valid: Object.keys(errors).length === 0, errors } } -exports.fetchEnrichedRow = async function(ctx) { +exports.fetchEnrichedRow = async function (ctx) { const appId = ctx.appId const db = new CouchDB(appId) const tableId = ctx.params.tableId @@ -399,13 +399,13 @@ exports.fetchEnrichedRow = async function(ctx) { // look up the actual rows based on the ids const response = await db.allDocs({ include_docs: true, - keys: linkVals.map(linkVal => linkVal.id), + keys: linkVals.map((linkVal) => linkVal.id), }) // need to include the IDs in these rows for any links they may have let linkedRows = await outputProcessing( appId, table, - response.rows.map(row => row.doc) + response.rows.map((row) => row.doc) ) // insert the link rows in the correct place throughout the main row for (let fieldName of Object.keys(table.schema)) { @@ -413,8 +413,8 @@ exports.fetchEnrichedRow = async function(ctx) { if (field.type === FieldTypes.LINK) { // find the links that pertain to this field, get their indexes const linkIndexes = linkVals - .filter(link => link.fieldName === fieldName) - .map(link => linkVals.indexOf(link)) + .filter((link) => link.fieldName === fieldName) + .map((link) => linkVals.indexOf(link)) // find the rows that the links state are linked to this field row[fieldName] = linkedRows.filter((linkRow, index) => linkIndexes.includes(index) @@ -430,7 +430,7 @@ async function bulkDelete(ctx) { const { rows } = ctx.request.body const db = new CouchDB(appId) - let updates = rows.map(row => + let updates = rows.map((row) => linkRows.updateLinks({ appId, eventType: linkRows.EventType.ROW_DELETE, @@ -441,7 +441,7 @@ async function bulkDelete(ctx) { // TODO remove special user case in future if (ctx.params.tableId === InternalTables.USER_METADATA) { updates = updates.concat( - rows.map(row => { + rows.map((row) => { ctx.params = { id: row._id, } @@ -449,11 +449,11 @@ async function bulkDelete(ctx) { }) ) } else { - await db.bulkDocs(rows.map(row => ({ ...row, _deleted: true }))) + await db.bulkDocs(rows.map((row) => ({ ...row, _deleted: true }))) } await Promise.all(updates) - rows.forEach(row => { + rows.forEach((row) => { ctx.eventEmitter && ctx.eventEmitter.emitRow(`row:delete`, appId, row) }) } diff --git a/packages/server/src/api/controllers/screen.js b/packages/server/src/api/controllers/screen.js index 6095d00c95..3638b41958 100644 --- a/packages/server/src/api/controllers/screen.js +++ b/packages/server/src/api/controllers/screen.js @@ -2,7 +2,7 @@ const CouchDB = require("../../db") const { getScreenParams, generateScreenID } = require("../../db/utils") const { AccessController } = require("../../utilities/security/roles") -exports.fetch = async ctx => { +exports.fetch = async (ctx) => { const appId = ctx.appId const db = new CouchDB(appId) @@ -12,7 +12,7 @@ exports.fetch = async ctx => { include_docs: true, }) ) - ).rows.map(element => element.doc) + ).rows.map((element) => element.doc) ctx.body = await new AccessController(appId).checkScreensAccess( screens, @@ -20,7 +20,7 @@ exports.fetch = async ctx => { ) } -exports.save = async ctx => { +exports.save = async (ctx) => { const appId = ctx.appId const db = new CouchDB(appId) let screen = ctx.request.body @@ -38,7 +38,7 @@ exports.save = async ctx => { } } -exports.destroy = async ctx => { +exports.destroy = async (ctx) => { const db = new CouchDB(ctx.appId) await db.remove(ctx.params.screenId, ctx.params.screenRev) ctx.body = { diff --git a/packages/server/src/api/controllers/search/index.js b/packages/server/src/api/controllers/search/index.js index 234c7eb258..87dc9a1f09 100644 --- a/packages/server/src/api/controllers/search/index.js +++ b/packages/server/src/api/controllers/search/index.js @@ -1,6 +1,6 @@ const { QueryBuilder, buildSearchUrl, search } = require("./utils") -exports.rowSearch = async ctx => { +exports.rowSearch = async (ctx) => { const appId = ctx.appId const { tableId } = ctx.params const { bookmark, query, raw } = ctx.request.body diff --git a/packages/server/src/api/controllers/search/utils.js b/packages/server/src/api/controllers/search/utils.js index d3ffb26be7..18c10ceb93 100644 --- a/packages/server/src/api/controllers/search/utils.js +++ b/packages/server/src/api/controllers/search/utils.js @@ -116,7 +116,7 @@ class QueryBuilder { } } -exports.search = async query => { +exports.search = async (query) => { const response = await fetch(query, { method: "GET", }) @@ -125,7 +125,7 @@ exports.search = async query => { rows: [], } if (json.rows != null && json.rows.length > 0) { - output.rows = json.rows.map(row => row.doc) + output.rows = json.rows.map((row) => row.doc) } if (json.bookmark) { output.bookmark = json.bookmark diff --git a/packages/server/src/api/controllers/static/index.js b/packages/server/src/api/controllers/static/index.js index a7b6fc8201..750297f8ef 100644 --- a/packages/server/src/api/controllers/static/index.js +++ b/packages/server/src/api/controllers/static/index.js @@ -15,7 +15,7 @@ const { TOP_LEVEL_PATH, } = require("../../../utilities/fileSystem") const env = require("../../../environment") -const fileProcessor = require("../../../utilities/fileSystem/processor") +// const fileProcessor = require("../../../utilities/fileSystem/processor") const { objectStoreUrl, clientLibraryPath } = require("../../../utilities") async function checkForSelfHostedURL(ctx) { @@ -32,18 +32,18 @@ async function checkForSelfHostedURL(ctx) { // this was the version before we started versioning the component library const COMP_LIB_BASE_APP_VERSION = "0.2.5" -exports.serveBuilder = async function(ctx) { +exports.serveBuilder = async function (ctx) { let builderPath = resolve(TOP_LEVEL_PATH, "builder") await send(ctx, ctx.file, { root: builderPath }) } -exports.uploadFile = async function(ctx) { +exports.uploadFile = async function (ctx) { let files = ctx.request.files.file.length > 1 ? Array.from(ctx.request.files.file) : [ctx.request.files.file] - const uploads = files.map(async file => { + const uploads = files.map(async (file) => { const fileExtension = [...file.name.split(".")].pop() // filenames converted to UUIDs so they are unique const processedFileName = `${uuid.v4()}.${fileExtension}` @@ -65,7 +65,7 @@ exports.uploadFile = async function(ctx) { ctx.body = await Promise.all(uploads) } -exports.serveApp = async function(ctx) { +exports.serveApp = async function (ctx) { let appId = ctx.params.appId if (env.SELF_HOSTED) { appId = await checkForSelfHostedURL(ctx) @@ -90,13 +90,13 @@ exports.serveApp = async function(ctx) { }) } -exports.serveClientLibrary = async function(ctx) { +exports.serveClientLibrary = async function (ctx) { return send(ctx, "budibase-client.js", { root: join(NODE_MODULES_PATH, "@budibase", "client", "dist"), }) } -exports.serveComponentLibrary = async function(ctx) { +exports.serveComponentLibrary = async function (ctx) { const appId = ctx.query.appId || ctx.appId if (env.isDev() || env.isTest()) { diff --git a/packages/server/src/api/controllers/table/index.js b/packages/server/src/api/controllers/table/index.js index 995ba8f72c..221febe6ff 100644 --- a/packages/server/src/api/controllers/table/index.js +++ b/packages/server/src/api/controllers/table/index.js @@ -9,22 +9,22 @@ const { const { FieldTypes } = require("../../../constants") const { TableSaveFunctions } = require("./utils") -exports.fetch = async function(ctx) { +exports.fetch = async function (ctx) { const db = new CouchDB(ctx.appId) const body = await db.allDocs( getTableParams(null, { include_docs: true, }) ) - ctx.body = body.rows.map(row => row.doc) + ctx.body = body.rows.map((row) => row.doc) } -exports.find = async function(ctx) { +exports.find = async function (ctx) { const db = new CouchDB(ctx.appId) ctx.body = await db.get(ctx.params.id) } -exports.save = async function(ctx) { +exports.save = async function (ctx) { const appId = ctx.appId const db = new CouchDB(appId) const { dataImport, ...rest } = ctx.request.body @@ -126,7 +126,7 @@ exports.save = async function(ctx) { ctx.body = tableToSave } -exports.destroy = async function(ctx) { +exports.destroy = async function (ctx) { const appId = ctx.appId const db = new CouchDB(appId) const tableToDelete = await db.get(ctx.params.tableId) @@ -137,7 +137,7 @@ exports.destroy = async function(ctx) { include_docs: true, }) ) - await db.bulkDocs(rows.rows.map(row => ({ ...row.doc, _deleted: true }))) + await db.bulkDocs(rows.rows.map((row) => ({ ...row.doc, _deleted: true }))) // update linked rows await linkRows.updateLinks({ @@ -152,7 +152,7 @@ exports.destroy = async function(ctx) { // remove table search index const currentIndexes = await db.getIndexes() const existingIndex = currentIndexes.indexes.find( - existing => existing.name === `search:${ctx.params.tableId}` + (existing) => existing.name === `search:${ctx.params.tableId}` ) if (existingIndex) { await db.deleteIndex(existingIndex) @@ -164,7 +164,7 @@ exports.destroy = async function(ctx) { ctx.body = { message: `Table ${ctx.params.tableId} deleted.` } } -exports.validateCSVSchema = async function(ctx) { +exports.validateCSVSchema = async function (ctx) { const { csvString, schema = {} } = ctx.request.body const result = await csvParser.parse(csvString, schema) ctx.body = { schema: result } diff --git a/packages/server/src/api/controllers/table/utils.js b/packages/server/src/api/controllers/table/utils.js index 3cf64e8e31..a549f248f5 100644 --- a/packages/server/src/api/controllers/table/utils.js +++ b/packages/server/src/api/controllers/table/utils.js @@ -16,7 +16,7 @@ exports.checkForColumnUpdates = async (db, oldTable, updatedTable) => { let deletedColumns = [] if (oldTable && oldTable.schema && updatedTable.schema) { deletedColumns = Object.keys(oldTable.schema).filter( - colName => updatedTable.schema[colName] == null + (colName) => updatedTable.schema[colName] == null ) } // check for renaming of columns or deleted columns @@ -31,7 +31,7 @@ exports.checkForColumnUpdates = async (db, oldTable, updatedTable) => { doc[rename.updated] = doc[rename.old] delete doc[rename.old] } else if (deletedColumns.length !== 0) { - deletedColumns.forEach(colName => delete doc[colName]) + deletedColumns.forEach((colName) => delete doc[colName]) } return doc }) @@ -102,12 +102,12 @@ exports.handleSearchIndexes = async (appId, table) => { const indexName = `search:${table._id}` const existingIndex = currentIndexes.indexes.find( - existing => existing.name === indexName + (existing) => existing.name === indexName ) if (existingIndex) { const currentFields = existingIndex.def.fields.map( - field => Object.keys(field)[0] + (field) => Object.keys(field)[0] ) // if index fields have changed, delete the original index @@ -138,7 +138,7 @@ exports.handleSearchIndexes = async (appId, table) => { return table } -exports.checkStaticTables = table => { +exports.checkStaticTables = (table) => { // check user schema has all required elements if (table._id === InternalTables.USER_METADATA) { for (let [key, schema] of Object.entries(USERS_TABLE_SCHEMA.schema)) { diff --git a/packages/server/src/api/controllers/templates.js b/packages/server/src/api/controllers/templates.js index 4d55bc5957..f650491d2b 100644 --- a/packages/server/src/api/controllers/templates.js +++ b/packages/server/src/api/controllers/templates.js @@ -5,7 +5,7 @@ const { downloadTemplate } = require("../../utilities/fileSystem") const DEFAULT_TEMPLATES_BUCKET = "prod-budi-templates.s3-eu-west-1.amazonaws.com" -exports.fetch = async function(ctx) { +exports.fetch = async function (ctx) { const { type = "app" } = ctx.query const response = await fetch( `https://${DEFAULT_TEMPLATES_BUCKET}/manifest.json` @@ -16,7 +16,7 @@ exports.fetch = async function(ctx) { // can't currently test this, have to ignore from coverage /* istanbul ignore next */ -exports.downloadTemplate = async function(ctx) { +exports.downloadTemplate = async function (ctx) { const { type, name } = ctx.params await downloadTemplate(type, name) diff --git a/packages/server/src/api/controllers/user.js b/packages/server/src/api/controllers/user.js index 1f41acc754..cbcebe93cc 100644 --- a/packages/server/src/api/controllers/user.js +++ b/packages/server/src/api/controllers/user.js @@ -13,7 +13,7 @@ const { } = require("../../utilities/workerRequests") const { getFullUser } = require("../../utilities/users") -exports.fetchMetadata = async function(ctx) { +exports.fetchMetadata = async function (ctx) { const database = new CouchDB(ctx.appId) const global = await getGlobalUsers(ctx, ctx.appId) const metadata = ( @@ -22,11 +22,11 @@ exports.fetchMetadata = async function(ctx) { include_docs: true, }) ) - ).rows.map(row => row.doc) + ).rows.map((row) => row.doc) const users = [] for (let user of global) { // find the metadata that matches up to the global ID - const info = metadata.find(meta => meta._id.includes(user._id)) + const info = metadata.find((meta) => meta._id.includes(user._id)) // remove these props, not for the correct DB users.push({ ...user, @@ -38,7 +38,7 @@ exports.fetchMetadata = async function(ctx) { ctx.body = users } -exports.createMetadata = async function(ctx) { +exports.createMetadata = async function (ctx) { const appId = ctx.appId const db = new CouchDB(appId) const { roleId } = ctx.request.body @@ -70,7 +70,7 @@ exports.createMetadata = async function(ctx) { } } -exports.updateSelfMetadata = async function(ctx) { +exports.updateSelfMetadata = async function (ctx) { // overwrite the ID with current users ctx.request.body._id = ctx.user._id // make sure no stale rev @@ -78,7 +78,7 @@ exports.updateSelfMetadata = async function(ctx) { await exports.updateMetadata(ctx) } -exports.updateMetadata = async function(ctx) { +exports.updateMetadata = async function (ctx) { const appId = ctx.appId const db = new CouchDB(appId) const user = ctx.request.body @@ -94,7 +94,7 @@ exports.updateMetadata = async function(ctx) { ctx.body = await db.put(metadata) } -exports.destroyMetadata = async function(ctx) { +exports.destroyMetadata = async function (ctx) { const db = new CouchDB(ctx.appId) await deleteGlobalUser(ctx, getGlobalIDFromUserMetadataID(ctx.params.id)) try { @@ -108,6 +108,6 @@ exports.destroyMetadata = async function(ctx) { } } -exports.findMetadata = async function(ctx) { +exports.findMetadata = async function (ctx) { ctx.body = await getFullUser(ctx, ctx.params.id) } diff --git a/packages/server/src/api/controllers/view/exporters.js b/packages/server/src/api/controllers/view/exporters.js index c1e5679d2a..bdd9ce1a3e 100644 --- a/packages/server/src/api/controllers/view/exporters.js +++ b/packages/server/src/api/controllers/view/exporters.js @@ -1,14 +1,14 @@ -exports.csv = function(headers, rows) { - let csv = headers.map(key => `"${key}"`).join(",") +exports.csv = function (headers, rows) { + let csv = headers.map((key) => `"${key}"`).join(",") for (let row of rows) { csv = `${csv}\n${headers - .map(header => `"${row[header]}"`.trim()) + .map((header) => `"${row[header]}"`.trim()) .join(",")}` } return csv } -exports.json = function(headers, rows) { +exports.json = function (headers, rows) { return JSON.stringify(rows, undefined, 2) } diff --git a/packages/server/src/api/controllers/view/index.js b/packages/server/src/api/controllers/view/index.js index 3d0f236fce..dc3b9c0bec 100644 --- a/packages/server/src/api/controllers/view/index.js +++ b/packages/server/src/api/controllers/view/index.js @@ -6,7 +6,7 @@ const { fetchView } = require("../row") const { ViewNames } = require("../../../db/utils") const controller = { - fetch: async ctx => { + fetch: async (ctx) => { const db = new CouchDB(ctx.appId) const designDoc = await db.get("_design/database") const response = [] @@ -24,7 +24,7 @@ const controller = { ctx.body = response }, - save: async ctx => { + save: async (ctx) => { const db = new CouchDB(ctx.appId) const { originalName, ...viewToSave } = ctx.request.body const designDoc = await db.get("_design/database") @@ -65,7 +65,7 @@ const controller = { name: viewToSave.name, } }, - destroy: async ctx => { + destroy: async (ctx) => { const db = new CouchDB(ctx.appId) const designDoc = await db.get("_design/database") const viewName = decodeURI(ctx.params.viewName) @@ -80,7 +80,7 @@ const controller = { ctx.body = view }, - exportView: async ctx => { + exportView: async (ctx) => { const db = new CouchDB(ctx.appId) const designDoc = await db.get("_design/database") const viewName = decodeURI(ctx.query.view) diff --git a/packages/server/src/api/controllers/webhook.js b/packages/server/src/api/controllers/webhook.js index c810f85004..f83de104fb 100644 --- a/packages/server/src/api/controllers/webhook.js +++ b/packages/server/src/api/controllers/webhook.js @@ -21,17 +21,17 @@ exports.WebhookType = { AUTOMATION: "automation", } -exports.fetch = async ctx => { +exports.fetch = async (ctx) => { const db = new CouchDB(ctx.appId) const response = await db.allDocs( getWebhookParams(null, { include_docs: true, }) ) - ctx.body = response.rows.map(row => row.doc) + ctx.body = response.rows.map((row) => row.doc) } -exports.save = async ctx => { +exports.save = async (ctx) => { const db = new CouchDB(ctx.appId) const webhook = ctx.request.body webhook.appId = ctx.appId @@ -50,12 +50,12 @@ exports.save = async ctx => { } } -exports.destroy = async ctx => { +exports.destroy = async (ctx) => { const db = new CouchDB(ctx.appId) ctx.body = await db.remove(ctx.params.id, ctx.params.rev) } -exports.buildSchema = async ctx => { +exports.buildSchema = async (ctx) => { const db = new CouchDB(ctx.params.instance) const webhook = await db.get(ctx.params.id) webhook.bodySchema = toJsonSchema(ctx.request.body) @@ -75,7 +75,7 @@ exports.buildSchema = async ctx => { ctx.body = await db.put(webhook) } -exports.trigger = async ctx => { +exports.trigger = async (ctx) => { const db = new CouchDB(ctx.params.instance) const webhook = await db.get(ctx.params.id) // validate against the schema diff --git a/packages/server/src/api/index.js b/packages/server/src/api/index.js index 369578d05e..1e1a9dd707 100644 --- a/packages/server/src/api/index.js +++ b/packages/server/src/api/index.js @@ -36,8 +36,8 @@ router } await next() }) - .use("/health", ctx => (ctx.status = 200)) - .use("/version", ctx => (ctx.body = pkg.version)) + .use("/health", (ctx) => (ctx.status = 200)) + .use("/version", (ctx) => (ctx.body = pkg.version)) .use(buildAuthMiddleware(NO_AUTH_ENDPOINTS)) .use(currentApp) @@ -58,7 +58,7 @@ router.use(async (ctx, next) => { } }) -router.get("/health", ctx => (ctx.status = 200)) +router.get("/health", (ctx) => (ctx.status = 200)) // authenticated routes for (let route of mainRoutes) { diff --git a/packages/server/src/api/routes/tests/utilities/TestFunctions.js b/packages/server/src/api/routes/tests/utilities/TestFunctions.js index 0e11dd2056..5ad3ed61be 100644 --- a/packages/server/src/api/routes/tests/utilities/TestFunctions.js +++ b/packages/server/src/api/routes/tests/utilities/TestFunctions.js @@ -7,7 +7,7 @@ function Request(appId, params) { this.params = params } -exports.getAllTableRows = async config => { +exports.getAllTableRows = async (config) => { const req = new Request(config.appId, { tableId: config.table._id }) await rowController.fetchTableRows(req) return req.body @@ -26,7 +26,7 @@ exports.clearAllApps = async () => { } } -exports.clearAllAutomations = async config => { +exports.clearAllAutomations = async (config) => { const automations = await config.getAllAutomations() for (let auto of automations) { await config.deleteAutomation(auto) @@ -88,6 +88,6 @@ exports.checkPermissionsEndpoint = async ({ .expect(403) } -exports.getDB = config => { +exports.getDB = (config) => { return new CouchDB(config.getAppId()) } diff --git a/packages/server/src/api/routes/tests/utilities/index.js b/packages/server/src/api/routes/tests/utilities/index.js index e9361aa67d..b8b9e04ec3 100644 --- a/packages/server/src/api/routes/tests/utilities/index.js +++ b/packages/server/src/api/routes/tests/utilities/index.js @@ -11,7 +11,7 @@ jest.mock("../../../../utilities/workerRequests", () => ({ }), })) -exports.delay = ms => new Promise(resolve => setTimeout(resolve, ms)) +exports.delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) let request, config @@ -44,7 +44,7 @@ exports.getConfig = () => { return config } -exports.switchToSelfHosted = async func => { +exports.switchToSelfHosted = async (func) => { // self hosted stops any attempts to Dynamo env._set("NODE_ENV", "production") env._set("SELF_HOSTED", true) diff --git a/packages/server/src/app.js b/packages/server/src/app.js index 2f3b977bbe..87435d68a8 100644 --- a/packages/server/src/app.js +++ b/packages/server/src/app.js @@ -47,8 +47,8 @@ if (electron.app && electron.app.isPackaged) { Sentry.init() app.on("error", (err, ctx) => { - Sentry.withScope(function(scope) { - scope.addEventProcessor(function(event) { + Sentry.withScope(function (scope) { + scope.addEventProcessor(function (event) { return Sentry.Handlers.parseRequest(event, ctx.request) }) Sentry.captureException(err) @@ -73,7 +73,7 @@ module.exports = server.listen(env.PORT || 0, async () => { await automations.init() }) -process.on("uncaughtException", err => { +process.on("uncaughtException", (err) => { console.error(err) server.close() server.destroy() diff --git a/packages/server/src/automations/actions.js b/packages/server/src/automations/actions.js index 9675568808..f211b52cd5 100644 --- a/packages/server/src/automations/actions.js +++ b/packages/server/src/automations/actions.js @@ -36,7 +36,7 @@ function buildBundleName(pkgName, version) { } /* istanbul ignore next */ -module.exports.getAction = async function(actionName) { +module.exports.getAction = async function (actionName) { if (BUILTIN_ACTIONS[actionName] != null) { return BUILTIN_ACTIONS[actionName] } @@ -53,7 +53,7 @@ module.exports.getAction = async function(actionName) { return getExternalAutomationStep(pkg.stepId, pkg.version, bundleName) } -module.exports.init = async function() { +module.exports.init = async function () { try { MANIFEST = await automationInit() module.exports.DEFINITIONS = diff --git a/packages/server/src/automations/index.js b/packages/server/src/automations/index.js index d67227e6ac..e50b853a9e 100644 --- a/packages/server/src/automations/index.js +++ b/packages/server/src/automations/index.js @@ -9,7 +9,7 @@ let workers = workerFarm(require.resolve("./thread")) function runWorker(job) { return new Promise((resolve, reject) => { - workers(job, err => { + workers(job, (err) => { if (err) { reject(err) } else { @@ -30,9 +30,9 @@ async function updateQuota(automation) { /** * This module is built purely to kick off the worker farm and manage the inputs/outputs */ -module.exports.init = async function() { +module.exports.init = async function () { await actions.init() - triggers.automationQueue.process(async job => { + triggers.automationQueue.process(async (job) => { try { if (env.USE_QUOTAS) { job.data.automation.apiKey = await updateQuota(job.data.automation) diff --git a/packages/server/src/automations/logic.js b/packages/server/src/automations/logic.js index b74c02bb56..cbd3d42430 100644 --- a/packages/server/src/automations/logic.js +++ b/packages/server/src/automations/logic.js @@ -11,7 +11,7 @@ let BUILTIN_DEFINITIONS = { FILTER: filter.definition, } -module.exports.getLogic = function(logicName) { +module.exports.getLogic = function (logicName) { if (BUILTIN_LOGIC[logicName] != null) { return BUILTIN_LOGIC[logicName] } diff --git a/packages/server/src/automations/steps/createRow.js b/packages/server/src/automations/steps/createRow.js index 9ab70d3161..889f7e98b9 100644 --- a/packages/server/src/automations/steps/createRow.js +++ b/packages/server/src/automations/steps/createRow.js @@ -58,7 +58,7 @@ module.exports.definition = { }, } -module.exports.run = async function({ inputs, appId, apiKey, emitter }) { +module.exports.run = async function ({ inputs, appId, apiKey, emitter }) { if (inputs.row == null || inputs.row.tableId == null) { return { success: false, diff --git a/packages/server/src/automations/steps/createUser.js b/packages/server/src/automations/steps/createUser.js index 2438c8fb78..6bdc784441 100644 --- a/packages/server/src/automations/steps/createUser.js +++ b/packages/server/src/automations/steps/createUser.js @@ -58,7 +58,7 @@ module.exports.definition = { }, } -module.exports.run = async function({ inputs, appId, apiKey, emitter }) { +module.exports.run = async function ({ inputs, appId, apiKey, emitter }) { const { email, password, roleId } = inputs const ctx = { appId, diff --git a/packages/server/src/automations/steps/deleteRow.js b/packages/server/src/automations/steps/deleteRow.js index 4d6fbb2a70..b6af7ecaab 100644 --- a/packages/server/src/automations/steps/deleteRow.js +++ b/packages/server/src/automations/steps/deleteRow.js @@ -50,7 +50,7 @@ module.exports.definition = { }, } -module.exports.run = async function({ inputs, appId, apiKey, emitter }) { +module.exports.run = async function ({ inputs, appId, apiKey, emitter }) { if (inputs.id == null || inputs.revision == null) { return { success: false, diff --git a/packages/server/src/automations/steps/outgoingWebhook.js b/packages/server/src/automations/steps/outgoingWebhook.js index ab8c747c58..f476d57ac5 100644 --- a/packages/server/src/automations/steps/outgoingWebhook.js +++ b/packages/server/src/automations/steps/outgoingWebhook.js @@ -64,7 +64,7 @@ module.exports.definition = { }, } -module.exports.run = async function({ inputs }) { +module.exports.run = async function ({ inputs }) { let { requestMethod, url, requestBody } = inputs if (!url.startsWith("http")) { url = `http://${url}` diff --git a/packages/server/src/automations/steps/sendEmail.js b/packages/server/src/automations/steps/sendEmail.js index 7f7438e58a..e08a3d8bc4 100644 --- a/packages/server/src/automations/steps/sendEmail.js +++ b/packages/server/src/automations/steps/sendEmail.js @@ -48,7 +48,7 @@ module.exports.definition = { }, } -module.exports.run = async function({ inputs }) { +module.exports.run = async function ({ inputs }) { const sgMail = require("@sendgrid/mail") sgMail.setApiKey(inputs.apiKey) const msg = { diff --git a/packages/server/src/automations/steps/updateRow.js b/packages/server/src/automations/steps/updateRow.js index 78c11a4212..f873eecbdb 100644 --- a/packages/server/src/automations/steps/updateRow.js +++ b/packages/server/src/automations/steps/updateRow.js @@ -53,7 +53,7 @@ module.exports.definition = { }, } -module.exports.run = async function({ inputs, appId, emitter }) { +module.exports.run = async function ({ inputs, appId, emitter }) { if (inputs.rowId == null || inputs.row == null) { return { success: false, diff --git a/packages/server/src/automations/tests/utilities/index.js b/packages/server/src/automations/tests/utilities/index.js index ab9de55430..7f65d08690 100644 --- a/packages/server/src/automations/tests/utilities/index.js +++ b/packages/server/src/automations/tests/utilities/index.js @@ -17,7 +17,7 @@ exports.afterAll = () => { config.end() } -exports.runInProd = async fn => { +exports.runInProd = async (fn) => { env._set("NODE_ENV", "production") env._set("USE_QUOTAS", 1) let error @@ -37,7 +37,7 @@ exports.runStep = async function runStep(stepId, inputs) { let step if ( Object.values(exports.actions) - .map(action => action.stepId) + .map((action) => action.stepId) .includes(stepId) ) { step = await actions.getAction(stepId) diff --git a/packages/server/src/automations/triggers.js b/packages/server/src/automations/triggers.js index 7e50e5ee74..8d97e095d2 100644 --- a/packages/server/src/automations/triggers.js +++ b/packages/server/src/automations/triggers.js @@ -204,8 +204,8 @@ async function queueRelevantRowAutomations(event, eventType) { // filter down to the correct event type automations = automations.rows - .map(automation => automation.doc) - .filter(automation => { + .map((automation) => automation.doc) + .filter((automation) => { const trigger = automation.definition.trigger return trigger && trigger.event === eventType }) @@ -224,7 +224,7 @@ async function queueRelevantRowAutomations(event, eventType) { } } -emitter.on("row:save", async function(event) { +emitter.on("row:save", async function (event) { /* istanbul ignore next */ if (!event || !event.row || !event.row.tableId) { return @@ -232,7 +232,7 @@ emitter.on("row:save", async function(event) { await queueRelevantRowAutomations(event, "row:save") }) -emitter.on("row:update", async function(event) { +emitter.on("row:update", async function (event) { /* istanbul ignore next */ if (!event || !event.row || !event.row.tableId) { return @@ -240,7 +240,7 @@ emitter.on("row:update", async function(event) { await queueRelevantRowAutomations(event, "row:update") }) -emitter.on("row:delete", async function(event) { +emitter.on("row:delete", async function (event) { /* istanbul ignore next */ if (!event || !event.row || !event.row.tableId) { return @@ -281,7 +281,7 @@ async function fillRowOutput(automation, params) { return params } -module.exports.externalTrigger = async function(automation, params) { +module.exports.externalTrigger = async function (automation, params) { // TODO: replace this with allowing user in builder to input values in future if (automation.definition != null && automation.definition.trigger != null) { if (automation.definition.trigger.inputs.tableId != null) { diff --git a/packages/server/src/constants/screens.js b/packages/server/src/constants/screens.js index ac6112a63f..0634758929 100644 --- a/packages/server/src/constants/screens.js +++ b/packages/server/src/constants/screens.js @@ -50,7 +50,7 @@ exports.createHomeScreen = () => ({ name: "home-screen", }) -exports.createLoginScreen = app => ({ +exports.createLoginScreen = (app) => ({ description: "", url: "", layoutId: BASE_LAYOUT_PROP_IDS.PUBLIC, diff --git a/packages/server/src/db/builder.js b/packages/server/src/db/builder.js index d2bbcd404b..21ff25d327 100644 --- a/packages/server/src/db/builder.js +++ b/packages/server/src/db/builder.js @@ -27,7 +27,7 @@ exports.getBuilderMainDoc = async () => { } } -exports.setBuilderMainDoc = async doc => { +exports.setBuilderMainDoc = async (doc) => { if (!env.SELF_HOSTED) { throw SELF_HOST_ERR } diff --git a/packages/server/src/db/client.js b/packages/server/src/db/client.js index 3e3a4f50fe..bf86603270 100644 --- a/packages/server/src/db/client.js +++ b/packages/server/src/db/client.js @@ -31,7 +31,7 @@ allDbs(Pouch) /* istanbul ignore next */ // eslint-disable-next-line no-unused-vars function replicateLocal() { - Pouch.allDbs().then(dbs => { + Pouch.allDbs().then((dbs) => { for (let db of dbs) { new Pouch(db).sync( new PouchDB(`http://127.0.0.1:5984/${db}`, { live: true }) diff --git a/packages/server/src/db/dynamoClient.js b/packages/server/src/db/dynamoClient.js index 19924b1a7e..59e21c6119 100644 --- a/packages/server/src/db/dynamoClient.js +++ b/packages/server/src/db/dynamoClient.js @@ -100,7 +100,7 @@ class Table { } } -exports.init = endpoint => { +exports.init = (endpoint) => { let AWS = require("aws-sdk") AWS.config.update({ region: AWS_REGION, diff --git a/packages/server/src/db/linkedRows/LinkController.js b/packages/server/src/db/linkedRows/LinkController.js index 53ce8e45ad..1be4bb9fec 100644 --- a/packages/server/src/db/linkedRows/LinkController.js +++ b/packages/server/src/db/linkedRows/LinkController.js @@ -194,11 +194,11 @@ class LinkController { if (field.type === FieldTypes.LINK && rowField != null) { // check which links actual pertain to the update in this row const thisFieldLinkDocs = linkDocs.filter( - linkDoc => + (linkDoc) => linkDoc.doc1.fieldName === fieldName || linkDoc.doc2.fieldName === fieldName ) - const linkDocIds = thisFieldLinkDocs.map(linkDoc => { + const linkDocIds = thisFieldLinkDocs.map((linkDoc) => { return linkDoc.doc1.rowId === row._id ? linkDoc.doc2.rowId : linkDoc.doc1.rowId @@ -218,7 +218,7 @@ class LinkController { rowId: linkId, includeDocs: IncludeDocs.EXCLUDE, }) - ).filter(link => link.id !== row._id) + ).filter((link) => link.id !== row._id) // The 1 side of 1:N is already related to something else // You must remove the existing relationship @@ -251,12 +251,12 @@ class LinkController { } // find the docs that need to be deleted let toDeleteDocs = thisFieldLinkDocs - .filter(doc => { + .filter((doc) => { let correctDoc = doc.doc1.fieldName === fieldName ? doc.doc2 : doc.doc1 return rowField.indexOf(correctDoc.rowId) === -1 }) - .map(doc => { + .map((doc) => { return { ...doc, _deleted: true } }) // now add the docs to be deleted to the bulk operation @@ -282,7 +282,7 @@ class LinkController { if (linkDocs.length === 0) { return null } - const toDelete = linkDocs.map(doc => { + const toDelete = linkDocs.map((doc) => { return { ...doc, _deleted: true, @@ -301,7 +301,7 @@ class LinkController { let oldTable = this._oldTable let field = oldTable.schema[fieldName] const linkDocs = await this.getTableLinkDocs() - let toDelete = linkDocs.filter(linkDoc => { + let toDelete = linkDocs.filter((linkDoc) => { let correctFieldName = linkDoc.doc1.tableId === oldTable._id ? linkDoc.doc1.fieldName @@ -309,7 +309,7 @@ class LinkController { return correctFieldName === fieldName }) await this._db.bulkDocs( - toDelete.map(doc => { + toDelete.map((doc) => { return { ...doc, _deleted: true, @@ -434,7 +434,7 @@ class LinkController { return null } // get link docs for this table and configure for deletion - const toDelete = linkDocs.map(doc => { + const toDelete = linkDocs.map((doc) => { return { ...doc, _deleted: true, diff --git a/packages/server/src/db/linkedRows/index.js b/packages/server/src/db/linkedRows/index.js index 8de2093fb2..0c129d62fa 100644 --- a/packages/server/src/db/linkedRows/index.js +++ b/packages/server/src/db/linkedRows/index.js @@ -33,11 +33,11 @@ exports.getLinkDocuments = getLinkDocuments exports.createLinkView = createLinkView async function getLinksForRows(appId, rows) { - const tableIds = [...new Set(rows.map(el => el.tableId))] + const tableIds = [...new Set(rows.map((el) => el.tableId))] // start by getting all the link values for performance reasons const responses = flatten( await Promise.all( - tableIds.map(tableId => + tableIds.map((tableId) => getLinkDocuments({ appId, tableId: tableId, @@ -51,7 +51,7 @@ async function getLinksForRows(appId, rows) { return getUniqueByProp( responses // create a unique ID which we can use for getting only unique ones - .map(el => ({ ...el, unique: el.id + el.thisId + el.fieldName })), + .map((el) => ({ ...el, unique: el.id + el.thisId + el.fieldName })), "unique" ) } @@ -68,7 +68,7 @@ async function getLinksForRows(appId, rows) { * @returns {Promise} When the update is complete this will respond successfully. Returns the row for * row operations and the table for table operations. */ -exports.updateLinks = async function({ +exports.updateLinks = async function ({ eventType, appId, row, @@ -127,8 +127,8 @@ exports.attachLinkIDs = async (appId, rows) => { for (let row of rows) { // find anything that matches the row's ID we are searching for and join it links - .filter(el => el.thisId === row._id) - .forEach(link => { + .filter((el) => el.thisId === row._id) + .forEach((link) => { if (row[link.fieldName] == null) { row[link.fieldName] = [] } @@ -154,21 +154,21 @@ exports.attachLinkedPrimaryDisplay = async (appId, table, rows) => { return rows } const db = new CouchDB(appId) - const links = (await getLinksForRows(appId, rows)).filter(link => - rows.some(row => row._id === link.thisId) + const links = (await getLinksForRows(appId, rows)).filter((link) => + rows.some((row) => row._id === link.thisId) ) - const linkedRowIds = links.map(link => link.id) + const linkedRowIds = links.map((link) => link.id) const linked = (await db.allDocs(getMultiIDParams(linkedRowIds))).rows.map( - row => row.doc + (row) => row.doc ) // will populate this as we find them const linkedTables = [] for (let row of rows) { - for (let link of links.filter(link => link.thisId === row._id)) { + for (let link of links.filter((link) => link.thisId === row._id)) { if (row[link.fieldName] == null) { row[link.fieldName] = [] } - const linkedRow = linked.find(row => row._id === link.id) + const linkedRow = linked.find((row) => row._id === link.id) const linkedTableId = linkedRow.tableId || getRelatedTableForField(table, link.fieldName) const linkedTable = await getLinkedTable(db, linkedTableId, linkedTables) diff --git a/packages/server/src/db/linkedRows/linkUtils.js b/packages/server/src/db/linkedRows/linkUtils.js index 9200a05b98..6c28918555 100644 --- a/packages/server/src/db/linkedRows/linkUtils.js +++ b/packages/server/src/db/linkedRows/linkUtils.js @@ -29,7 +29,7 @@ exports.createLinkView = createLinkView * @returns {Promise} This will return an array of the linking documents that were found * (if any). */ -exports.getLinkDocuments = async function({ +exports.getLinkDocuments = async function ({ appId, tableId, rowId, @@ -49,7 +49,7 @@ exports.getLinkDocuments = async function({ let linkRows = (await db.query(getQueryIndex(ViewNames.LINK), params)).rows // filter to get unique entries const foundIds = [] - linkRows = linkRows.filter(link => { + linkRows = linkRows.filter((link) => { // make sure anything unique is the correct key if ( (tableId && link.key[0] !== tableId) || @@ -65,9 +65,9 @@ exports.getLinkDocuments = async function({ }) if (includeDocs) { - return linkRows.map(row => row.doc) + return linkRows.map((row) => row.doc) } else { - return linkRows.map(row => row.value) + return linkRows.map((row) => row.value) } } catch (err) { // check if the view doesn't exist, it should for all new instances @@ -83,18 +83,18 @@ exports.getLinkDocuments = async function({ exports.getUniqueByProp = (array, prop) => { return array.filter((obj, pos, arr) => { - return arr.map(mapObj => mapObj[prop]).indexOf(obj[prop]) === pos + return arr.map((mapObj) => mapObj[prop]).indexOf(obj[prop]) === pos }) } -exports.getLinkedTableIDs = table => { +exports.getLinkedTableIDs = (table) => { return Object.values(table.schema) - .filter(column => column.type === FieldTypes.LINK) - .map(column => column.tableId) + .filter((column) => column.type === FieldTypes.LINK) + .map((column) => column.tableId) } exports.getLinkedTable = async (db, id, tables) => { - let linkedTable = tables.find(table => table._id === id) + let linkedTable = tables.find((table) => table._id === id) if (linkedTable) { return linkedTable } diff --git a/packages/server/src/db/newid.js b/packages/server/src/db/newid.js index 6af467480d..b4f5e51c07 100644 --- a/packages/server/src/db/newid.js +++ b/packages/server/src/db/newid.js @@ -1,5 +1,5 @@ const { v4 } = require("uuid") -module.exports = function() { +module.exports = function () { return v4().replace(/-/g, "") } diff --git a/packages/server/src/db/utils.js b/packages/server/src/db/utils.js index bbed248cf8..0d492cde33 100644 --- a/packages/server/src/db/utils.js +++ b/packages/server/src/db/utils.js @@ -52,7 +52,7 @@ exports.SEPARATOR = SEPARATOR exports.UNICODE_MAX = UNICODE_MAX exports.SearchIndexes = SearchIndexes -exports.getQueryIndex = viewName => { +exports.getQueryIndex = (viewName) => { return `database/${viewName}` } @@ -135,14 +135,14 @@ exports.getUserMetadataParams = (userId = null, otherProps = {}) => { * @param {string} globalId The ID of the global user. * @returns {string} The new user ID which the user doc can be stored under. */ -exports.generateUserMetadataID = globalId => { +exports.generateUserMetadataID = (globalId) => { return exports.generateRowID(InternalTables.USER_METADATA, globalId) } /** * Breaks up the ID to get the global ID. */ -exports.getGlobalIDFromUserMetadataID = id => { +exports.getGlobalIDFromUserMetadataID = (id) => { return id.split( `${DocumentTypes.ROW}${SEPARATOR}${InternalTables.USER_METADATA}${SEPARATOR}` )[1] @@ -214,7 +214,7 @@ exports.getAppParams = (appId = null, otherProps = {}) => { * Generates a new role ID. * @returns {string} The new role ID which the role doc can be stored under. */ -exports.generateRoleID = id => { +exports.generateRoleID = (id) => { return `${DocumentTypes.ROLE}${SEPARATOR}${id || newid()}` } @@ -229,7 +229,7 @@ exports.getRoleParams = (roleId = null, otherProps = {}) => { * Generates a new layout ID. * @returns {string} The new layout ID which the layout doc can be stored under. */ -exports.generateLayoutID = id => { +exports.generateLayoutID = (id) => { return `${DocumentTypes.LAYOUT}${SEPARATOR}${id || newid()}` } @@ -289,7 +289,7 @@ exports.getDatasourceParams = (datasourceId = null, otherProps = {}) => { * Generates a new query ID. * @returns {string} The new query ID which the query doc can be stored under. */ -exports.generateQueryID = datasourceId => { +exports.generateQueryID = (datasourceId) => { return `${ DocumentTypes.QUERY }${SEPARATOR}${datasourceId}${SEPARATOR}${newid()}` @@ -313,7 +313,7 @@ exports.getQueryParams = (datasourceId = null, otherProps = {}) => { /** * This can be used with the db.allDocs to get a list of IDs */ -exports.getMultiIDParams = ids => { +exports.getMultiIDParams = (ids) => { return { keys: ids, include_docs: true, diff --git a/packages/server/src/db/views/staticViews.js b/packages/server/src/db/views/staticViews.js index 305d042217..f1fcd05275 100644 --- a/packages/server/src/db/views/staticViews.js +++ b/packages/server/src/db/views/staticViews.js @@ -25,11 +25,11 @@ const SCREEN_PREFIX = DocumentTypes.SCREEN + SEPARATOR * @returns {Promise} The view now exists, please note that the next view of this query will actually build it, * so it may be slow. */ -exports.createLinkView = async appId => { +exports.createLinkView = async (appId) => { const db = new CouchDB(appId) const designDoc = await db.get("_design/database") const view = { - map: function(doc) { + map: function (doc) { // everything in this must remain constant as its going to Pouch, no external variables if (doc.type === "link") { let doc1 = doc.doc1 @@ -57,7 +57,7 @@ exports.createLinkView = async appId => { await db.put(designDoc) } -exports.createRoutingView = async appId => { +exports.createRoutingView = async (appId) => { const db = new CouchDB(appId) const designDoc = await db.get("_design/database") const view = { @@ -89,11 +89,11 @@ async function searchIndex(appId, indexName, fnString) { await db.put(designDoc) } -exports.createAllSearchIndex = async appId => { +exports.createAllSearchIndex = async (appId) => { await searchIndex( appId, SearchIndexes.ROWS, - function(doc) { + function (doc) { function idx(input, prev) { for (let key of Object.keys(input)) { const idxKey = prev != null ? `${prev}.${key}` : key diff --git a/packages/server/src/integrations/couchdb.js b/packages/server/src/integrations/couchdb.js index df58b0e487..3dd6a5898f 100644 --- a/packages/server/src/integrations/couchdb.js +++ b/packages/server/src/integrations/couchdb.js @@ -61,7 +61,7 @@ class CouchDBIntegration { include_docs: true, ...query.json, }) - return result.rows.map(row => row.doc) + return result.rows.map((row) => row.doc) } catch (err) { console.error("Error querying couchDB", err) throw err diff --git a/packages/server/src/middleware/joi-validator.js b/packages/server/src/middleware/joi-validator.js index 1686b0e727..8e5feab255 100644 --- a/packages/server/src/middleware/joi-validator.js +++ b/packages/server/src/middleware/joi-validator.js @@ -19,10 +19,10 @@ function validate(schema, property) { } } -module.exports.body = schema => { +module.exports.body = (schema) => { return validate(schema, "body") } -module.exports.params = schema => { +module.exports.params = (schema) => { return validate(schema, "params") } diff --git a/packages/server/src/middleware/resourceId.js b/packages/server/src/middleware/resourceId.js index 4216131119..1c677f6b9e 100644 --- a/packages/server/src/middleware/resourceId.js +++ b/packages/server/src/middleware/resourceId.js @@ -38,7 +38,7 @@ class ResourceIdGetter { module.exports.ResourceIdGetter = ResourceIdGetter -module.exports.paramResource = main => { +module.exports.paramResource = (main) => { return new ResourceIdGetter("params").mainResource(main).build() } @@ -49,7 +49,7 @@ module.exports.paramSubResource = (main, sub) => { .build() } -module.exports.bodyResource = main => { +module.exports.bodyResource = (main) => { return new ResourceIdGetter("body").mainResource(main).build() } diff --git a/packages/server/src/middleware/usageQuota.js b/packages/server/src/middleware/usageQuota.js index ac8336e769..02d1f6d13c 100644 --- a/packages/server/src/middleware/usageQuota.js +++ b/packages/server/src/middleware/usageQuota.js @@ -54,7 +54,7 @@ module.exports = async (ctx, next) => { ctx.request.files.file.length > 1 ? Array.from(ctx.request.files.file) : [ctx.request.files.file] - usage = files.map(file => file.size).reduce((total, size) => total + size) + usage = files.map((file) => file.size).reduce((total, size) => total + size) } try { await usageQuota.update(ctx.auth.apiKey, property, usage) diff --git a/packages/server/src/tests/utilities/TestConfiguration.js b/packages/server/src/tests/utilities/TestConfiguration.js index c031cf082d..34d5bf0da5 100644 --- a/packages/server/src/tests/utilities/TestConfiguration.js +++ b/packages/server/src/tests/utilities/TestConfiguration.js @@ -89,7 +89,7 @@ class TestConfiguration { if (this.server) { this.server.close() } - cleanup(this.allApps.map(app => app._id)) + cleanup(this.allApps.map((app) => app._id)) } defaultHeaders() { diff --git a/packages/server/src/tests/utilities/index.js b/packages/server/src/tests/utilities/index.js index aa8039ce2f..46bbae470a 100644 --- a/packages/server/src/tests/utilities/index.js +++ b/packages/server/src/tests/utilities/index.js @@ -1,4 +1,4 @@ -exports.makePartial = obj => { +exports.makePartial = (obj) => { const newObj = {} for (let key of Object.keys(obj)) { if (typeof obj[key] === "object") { diff --git a/packages/server/src/tests/utilities/structures.js b/packages/server/src/tests/utilities/structures.js index 5e27ff4a3b..b3a103adf2 100644 --- a/packages/server/src/tests/utilities/structures.js +++ b/packages/server/src/tests/utilities/structures.js @@ -44,7 +44,7 @@ exports.basicAutomation = () => { } } -exports.basicRow = tableId => { +exports.basicRow = (tableId) => { return { name: "Test Contact", description: "original description", @@ -78,7 +78,7 @@ exports.basicDatasource = () => { } } -exports.basicQuery = datasourceId => { +exports.basicQuery = (datasourceId) => { return { datasourceId: datasourceId, name: "New Query", @@ -89,7 +89,7 @@ exports.basicQuery = datasourceId => { } } -exports.basicUser = role => { +exports.basicUser = (role) => { return { email: "bill@bill.com", password: "yeeooo", @@ -105,7 +105,7 @@ exports.basicLayout = () => { return cloneDeep(EMPTY_LAYOUT) } -exports.basicWebhook = automationId => { +exports.basicWebhook = (automationId) => { return { live: true, name: "webhook", diff --git a/packages/server/src/utilities/bcrypt.js b/packages/server/src/utilities/bcrypt.js index 6c52d2c2c7..1457afb350 100644 --- a/packages/server/src/utilities/bcrypt.js +++ b/packages/server/src/utilities/bcrypt.js @@ -5,7 +5,7 @@ const env = require("../environment") const SALT_ROUNDS = env.SALT_ROUNDS || 10 -exports.hash = async data => { +exports.hash = async (data) => { const salt = await bcrypt.genSalt(SALT_ROUNDS) const result = await bcrypt.hash(data, salt) return result diff --git a/packages/server/src/utilities/budibaseDir.js b/packages/server/src/utilities/budibaseDir.js index e27c45b9e0..f8cf3251ec 100644 --- a/packages/server/src/utilities/budibaseDir.js +++ b/packages/server/src/utilities/budibaseDir.js @@ -2,10 +2,10 @@ const { join } = require("./centralPath") const { homedir, tmpdir } = require("os") const env = require("../environment") -module.exports.budibaseAppsDir = function() { +module.exports.budibaseAppsDir = function () { return env.BUDIBASE_DIR || join(homedir(), ".budibase") } -module.exports.budibaseTempDir = function() { +module.exports.budibaseTempDir = function () { return join(tmpdir(), ".budibase") } diff --git a/packages/server/src/utilities/builder/hosting.js b/packages/server/src/utilities/builder/hosting.js index 271e4a1b07..73ce93e261 100644 --- a/packages/server/src/utilities/builder/hosting.js +++ b/packages/server/src/utilities/builder/hosting.js @@ -42,7 +42,7 @@ exports.getHostingInfo = async () => { return doc } -exports.getAppUrl = async appId => { +exports.getAppUrl = async (appId) => { const hostingInfo = await exports.getHostingInfo() const protocol = getProtocol(hostingInfo) let url diff --git a/packages/server/src/utilities/centralPath.js b/packages/server/src/utilities/centralPath.js index 030ba55fc5..4ce7bcfbb3 100644 --- a/packages/server/src/utilities/centralPath.js +++ b/packages/server/src/utilities/centralPath.js @@ -8,7 +8,7 @@ const path = require("path") * @param args Any number of string arguments to add to a path * @returns {string} The final path ready to use */ -exports.join = function(...args) { +exports.join = function (...args) { return path.join(...args) } @@ -17,6 +17,6 @@ exports.join = function(...args) { * @param args Any number of string arguments to add to a path * @returns {string} The final path ready to use */ -exports.resolve = function(...args) { +exports.resolve = function (...args) { return path.resolve(...args) } diff --git a/packages/server/src/utilities/csvParser.js b/packages/server/src/utilities/csvParser.js index 3ae020eb65..fe63eb9075 100644 --- a/packages/server/src/utilities/csvParser.js +++ b/packages/server/src/utilities/csvParser.js @@ -2,13 +2,13 @@ const csv = require("csvtojson") const VALIDATORS = { string: () => true, - number: attribute => !isNaN(Number(attribute)), - datetime: attribute => !isNaN(new Date(attribute).getTime()), + number: (attribute) => !isNaN(Number(attribute)), + datetime: (attribute) => !isNaN(new Date(attribute).getTime()), } const PARSERS = { - number: attribute => Number(attribute), - datetime: attribute => new Date(attribute).toISOString(), + number: (attribute) => Number(attribute), + datetime: (attribute) => new Date(attribute).toISOString(), } function parse(csvString, parsers) { @@ -17,7 +17,7 @@ function parse(csvString, parsers) { const schema = {} return new Promise((resolve, reject) => { - result.on("header", headers => { + result.on("header", (headers) => { for (let header of headers) { schema[header] = { type: parsers[header] ? parsers[header].type : "string", @@ -25,7 +25,7 @@ function parse(csvString, parsers) { } } }) - result.subscribe(row => { + result.subscribe((row) => { // For each CSV row parse all the columns that need parsed for (let key in parsers) { if (!schema[key] || schema[key].success) { @@ -41,7 +41,7 @@ function parse(csvString, parsers) { } } }) - result.on("done", error => { + result.on("done", (error) => { if (error) { console.error(error) reject(error) diff --git a/packages/server/src/utilities/fileSystem/index.js b/packages/server/src/utilities/fileSystem/index.js index d84c6deb8a..64a9960c80 100644 --- a/packages/server/src/utilities/fileSystem/index.js +++ b/packages/server/src/utilities/fileSystem/index.js @@ -73,7 +73,7 @@ exports.checkDevelopmentEnvironment = () => { * @param {Object} template The template object retrieved from the Koa context object. * @returns {Object} Returns an fs read stream which can be loaded into the database. */ -exports.getTemplateStream = async template => { +exports.getTemplateStream = async (template) => { if (template.file) { return fs.createReadStream(template.file.path) } else { @@ -89,7 +89,7 @@ exports.getTemplateStream = async template => { * @param {string} path The path to the handlebars file which is to be loaded. * @returns {string} The loaded handlebars file as a string - loaded as utf8. */ -exports.loadHandlebarsFile = path => { +exports.loadHandlebarsFile = (path) => { return fs.readFileSync(path, "utf8") } @@ -99,7 +99,7 @@ exports.loadHandlebarsFile = path => { * @param {string} contents the contents of the file which is to be returned from the API. * @return {Object} the read stream which can be put into the koa context body. */ -exports.apiFileReturn = contents => { +exports.apiFileReturn = (contents) => { const path = join(budibaseTempDir(), uuid()) fs.writeFileSync(path, contents) return fs.createReadStream(path) @@ -132,7 +132,7 @@ exports.performBackup = async (appId, backupName) => { * @param {string} appId The ID of the app which is being created. * @return {Promise} once promise completes app resources should be ready in object store. */ -exports.createApp = async appId => { +exports.createApp = async (appId) => { await downloadLibraries(appId) await newAppPublicPath(appId) } @@ -142,7 +142,7 @@ exports.createApp = async appId => { * @param {string} appId The ID of the app which is being deleted. * @return {Promise} once promise completes the app resources will be removed from object store. */ -exports.deleteApp = async appId => { +exports.deleteApp = async (appId) => { await deleteFolder(ObjectStoreBuckets.APPS, `${appId}/`) } @@ -225,7 +225,7 @@ exports.readFileSync = (filepath, options = "utf8") => { /** * Given a set of app IDs makes sure file system is cleared of any of their temp info. */ -exports.cleanup = appIds => { +exports.cleanup = (appIds) => { for (let appId of appIds) { fs.rmdirSync(join(budibaseTempDir(), appId), { recursive: true }) } diff --git a/packages/server/src/utilities/fileSystem/newApp.js b/packages/server/src/utilities/fileSystem/newApp.js index 91cc771743..ae2c6d1bbd 100644 --- a/packages/server/src/utilities/fileSystem/newApp.js +++ b/packages/server/src/utilities/fileSystem/newApp.js @@ -8,7 +8,7 @@ const BUCKET_NAME = ObjectStoreBuckets.APPS // can't really test this due to the downloading nature of it, wouldn't be a great test case /* istanbul ignore next */ -exports.downloadLibraries = async appId => { +exports.downloadLibraries = async (appId) => { const LIBRARIES = ["standard-components"] const paths = {} @@ -26,7 +26,7 @@ exports.downloadLibraries = async appId => { return paths } -exports.newAppPublicPath = async appId => { +exports.newAppPublicPath = async (appId) => { const path = join(appId, "public") const sourcepath = require.resolve("@budibase/client") const destPath = join(path, "budibase-client.js") diff --git a/packages/server/src/utilities/fileSystem/processor.js b/packages/server/src/utilities/fileSystem/processor.js index 3778b50168..1ad608bf1c 100644 --- a/packages/server/src/utilities/fileSystem/processor.js +++ b/packages/server/src/utilities/fileSystem/processor.js @@ -6,7 +6,7 @@ const FORMATS = { function processImage(file) { // this will overwrite the temp file - return jimp.read(file.path).then(img => { + return jimp.read(file.path).then((img) => { return img.resize(300, jimp.AUTO).write(file.path) }) } diff --git a/packages/server/src/utilities/fileSystem/utilities.js b/packages/server/src/utilities/fileSystem/utilities.js index b586cfcfe5..8103b734dd 100644 --- a/packages/server/src/utilities/fileSystem/utilities.js +++ b/packages/server/src/utilities/fileSystem/utilities.js @@ -53,7 +53,7 @@ const PUBLIC_BUCKETS = [ObjectStoreBuckets.APPS] * @return {Object} an S3 object store object, check S3 Nodejs SDK for usage. * @constructor */ -exports.ObjectStore = bucket => { +exports.ObjectStore = (bucket) => { if (env.SELF_HOSTED) { AWS.config.update({ accessKeyId: env.MINIO_ACCESS_KEY, @@ -199,7 +199,7 @@ exports.deleteFolder = async (bucket, folder) => { }, } - response.Contents.forEach(content => { + response.Contents.forEach((content) => { deleteParams.Delete.Objects.push({ Key: content.Key }) }) diff --git a/packages/server/src/utilities/index.js b/packages/server/src/utilities/index.js index 4210e6678b..041e558004 100644 --- a/packages/server/src/utilities/index.js +++ b/packages/server/src/utilities/index.js @@ -6,7 +6,7 @@ const { OBJ_STORE_DIRECTORY, ObjectStoreBuckets } = require("../constants") const BB_CDN = "https://cdn.app.budi.live/assets" const APP_PREFIX = DocumentTypes.APP + SEPARATOR -exports.wait = ms => new Promise(resolve => setTimeout(resolve, ms)) +exports.wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) exports.isDev = env.isDev @@ -19,14 +19,14 @@ exports.isDev = env.isDev */ exports.getAllApps = async () => { let allDbs = await CouchDB.allDbs() - const appDbNames = allDbs.filter(dbName => dbName.startsWith(APP_PREFIX)) - const appPromises = appDbNames.map(db => new CouchDB(db).get(db)) + const appDbNames = allDbs.filter((dbName) => dbName.startsWith(APP_PREFIX)) + const appPromises = appDbNames.map((db) => new CouchDB(db).get(db)) if (appPromises.length === 0) { return [] } else { const response = await Promise.allSettled(appPromises) return response - .filter(result => result.status === "fulfilled") + .filter((result) => result.status === "fulfilled") .map(({ value }) => value) } } @@ -37,7 +37,7 @@ exports.getAllApps = async () => { * @param {string} url The URL to test and remove any extra double slashes. * @return {string} The updated url. */ -exports.checkSlashesInUrl = url => { +exports.checkSlashesInUrl = (url) => { return url.replace(/(https?:\/\/)|(\/)+/g, "$1$2") } @@ -63,7 +63,7 @@ exports.objectStoreUrl = () => { * @return {string} The URL to be inserted into appPackage response or server rendered * app index file. */ -exports.clientLibraryPath = appId => { +exports.clientLibraryPath = (appId) => { if (env.isProd()) { return `${exports.objectStoreUrl()}/${appId}/budibase-client.js` } else { @@ -71,7 +71,7 @@ exports.clientLibraryPath = appId => { } } -exports.attachmentsRelativeURL = attachmentKey => { +exports.attachmentsRelativeURL = (attachmentKey) => { return exports.checkSlashesInUrl( `/${ObjectStoreBuckets.APPS}/${attachmentKey}` ) diff --git a/packages/server/src/utilities/routing/index.js b/packages/server/src/utilities/routing/index.js index 541733dcc4..223eef7664 100644 --- a/packages/server/src/utilities/routing/index.js +++ b/packages/server/src/utilities/routing/index.js @@ -2,14 +2,14 @@ const CouchDB = require("../../db") const { createRoutingView } = require("../../db/views/staticViews") const { ViewNames, getQueryIndex, UNICODE_MAX } = require("../../db/utils") -exports.getRoutingInfo = async appId => { +exports.getRoutingInfo = async (appId) => { const db = new CouchDB(appId) try { const allRouting = await db.query(getQueryIndex(ViewNames.ROUTING), { startKey: "", endKey: UNICODE_MAX, }) - return allRouting.rows.map(row => row.value) + return allRouting.rows.map((row) => row.value) } catch (err) { // check if the view doesn't exist, it should for all new instances /* istanbul ignore next */ diff --git a/packages/server/src/utilities/rowProcessor.js b/packages/server/src/utilities/rowProcessor.js index 4b94b517a3..28a0ee51ac 100644 --- a/packages/server/src/utilities/rowProcessor.js +++ b/packages/server/src/utilities/rowProcessor.js @@ -1,4 +1,4 @@ -const { ObjectStoreBuckets } = require("../constants") +// const { ObjectStoreBuckets } = require("../constants") const linkRows = require("../db/linkedRows") const { cloneDeep } = require("lodash/fp") const { FieldTypes, AutoFieldSubTypes } = require("../constants") @@ -14,9 +14,9 @@ const TYPE_TRANSFORM_MAP = { "": [], [null]: [], [undefined]: undefined, - parse: link => { + parse: (link) => { if (Array.isArray(link) && typeof link[0] === "object") { - return link.map(el => (el && el._id ? el._id : el)) + return link.map((el) => (el && el._id ? el._id : el)) } if (typeof link === "string") { return [link] @@ -43,13 +43,13 @@ const TYPE_TRANSFORM_MAP = { "": null, [null]: null, [undefined]: undefined, - parse: n => parseFloat(n), + parse: (n) => parseFloat(n), }, [FieldTypes.DATETIME]: { "": null, [undefined]: undefined, [null]: null, - parse: date => { + parse: (date) => { if (date instanceof Date) { return date.toISOString() } @@ -186,7 +186,7 @@ exports.outputProcessing = async (appId, table, rows) => { if (row[property] == null || row[property].length === 0) { continue } - row[property].forEach(attachment => { + row[property].forEach((attachment) => { attachment.url = attachmentsRelativeURL(attachment.key) }) } diff --git a/packages/server/src/utilities/security/permissions.js b/packages/server/src/utilities/security/permissions.js index 03fa5fa562..33d42a9414 100644 --- a/packages/server/src/utilities/security/permissions.js +++ b/packages/server/src/utilities/security/permissions.js @@ -126,9 +126,9 @@ exports.getBuiltinPermissions = () => { return cloneDeep(BUILTIN_PERMISSIONS) } -exports.getBuiltinPermissionByID = id => { +exports.getBuiltinPermissionByID = (id) => { const perms = Object.values(BUILTIN_PERMISSIONS) - return perms.find(perm => perm._id === id) + return perms.find((perm) => perm._id === id) } exports.doesHaveResourcePermission = ( @@ -163,8 +163,8 @@ exports.doesHaveBasePermission = (permType, permLevel, permissionIds) => { const builtins = Object.values(BUILTIN_PERMISSIONS) let permissions = flatten( builtins - .filter(builtin => permissionIds.indexOf(builtin._id) !== -1) - .map(builtin => builtin.permissions) + .filter((builtin) => permissionIds.indexOf(builtin._id) !== -1) + .map((builtin) => builtin.permissions) ) for (let permission of permissions) { if ( @@ -181,7 +181,7 @@ exports.higherPermission = (perm1, perm2) => { return levelToNumber(perm1) > levelToNumber(perm2) ? perm1 : perm2 } -exports.isPermissionLevelHigherThanRead = level => { +exports.isPermissionLevelHigherThanRead = (level) => { return levelToNumber(level) > 1 } diff --git a/packages/server/src/utilities/security/roles.js b/packages/server/src/utilities/security/roles.js index b0cd843591..3517235d00 100644 --- a/packages/server/src/utilities/security/roles.js +++ b/packages/server/src/utilities/security/roles.js @@ -16,12 +16,12 @@ function Role(id, name) { this.name = name } -Role.prototype.addPermission = function(permissionId) { +Role.prototype.addPermission = function (permissionId) { this.permissionId = permissionId return this } -Role.prototype.addInheritance = function(inherits) { +Role.prototype.addInheritance = function (inherits) { this.inherits = inherits return this } @@ -49,15 +49,15 @@ exports.getBuiltinRoles = () => { } exports.BUILTIN_ROLE_ID_ARRAY = Object.values(BUILTIN_ROLES).map( - role => role._id + (role) => role._id ) exports.BUILTIN_ROLE_NAME_ARRAY = Object.values(BUILTIN_ROLES).map( - role => role.name + (role) => role.name ) function isBuiltin(role) { - return exports.BUILTIN_ROLE_ID_ARRAY.some(builtin => role.includes(builtin)) + return exports.BUILTIN_ROLE_ID_ARRAY.some((builtin) => role.includes(builtin)) } /** @@ -112,7 +112,7 @@ exports.getRole = async (appId, roleId) => { // but can be extended by a doc stored about them (e.g. permissions) if (isBuiltin(roleId)) { role = cloneDeep( - Object.values(BUILTIN_ROLES).find(role => role._id === roleId) + Object.values(BUILTIN_ROLES).find((role) => role._id === roleId) ) } try { @@ -163,7 +163,7 @@ async function getAllUserRoles(appId, userRoleId) { */ exports.getUserRoleHierarchy = async (appId, userRoleId) => { // special case, if they don't have a role then they are a public user - return (await getAllUserRoles(appId, userRoleId)).map(role => role._id) + return (await getAllUserRoles(appId, userRoleId)).map((role) => role._id) } /** @@ -176,7 +176,7 @@ exports.getUserRoleHierarchy = async (appId, userRoleId) => { exports.getUserPermissions = async (appId, userRoleId) => { const rolesHierarchy = await getAllUserRoles(appId, userRoleId) const basePermissions = [ - ...new Set(rolesHierarchy.map(role => role.permissionId)), + ...new Set(rolesHierarchy.map((role) => role.permissionId)), ] const permissions = {} for (let role of rolesHierarchy) { @@ -245,7 +245,7 @@ class AccessController { /** * Adds the "role_" for builtin role IDs which are to be written to the DB (for permissions). */ -exports.getDBRoleID = roleId => { +exports.getDBRoleID = (roleId) => { if (roleId.startsWith(DocumentTypes.ROLE)) { return roleId } @@ -255,7 +255,7 @@ exports.getDBRoleID = roleId => { /** * Remove the "role_" from builtin role IDs that have been written to the DB (for permissions). */ -exports.getExternalRoleID = roleId => { +exports.getExternalRoleID = (roleId) => { // for built in roles we want to remove the DB role ID element (role_) if (roleId.startsWith(DocumentTypes.ROLE) && isBuiltin(roleId)) { return roleId.split(`${DocumentTypes.ROLE}${SEPARATOR}`)[1] diff --git a/packages/server/src/utilities/security/utilities.js b/packages/server/src/utilities/security/utilities.js index f22b11dbd3..1cd6543dcb 100644 --- a/packages/server/src/utilities/security/utilities.js +++ b/packages/server/src/utilities/security/utilities.js @@ -15,8 +15,8 @@ const CURRENTLY_SUPPORTED_LEVELS = [ PermissionLevels.READ, ] -exports.getPermissionType = resourceId => { - const docType = Object.values(DocumentTypes).filter(docType => +exports.getPermissionType = (resourceId) => { + const docType = Object.values(DocumentTypes).filter((docType) => resourceId.startsWith(docType) )[0] switch (docType) { @@ -41,7 +41,7 @@ exports.getPermissionType = resourceId => { * @param resourceId * @returns {{}} */ -exports.getBasePermissions = resourceId => { +exports.getBasePermissions = (resourceId) => { const type = exports.getPermissionType(resourceId) const permissions = {} for (let [roleId, role] of Object.entries(getBuiltinRoles())) { @@ -49,7 +49,7 @@ exports.getBasePermissions = resourceId => { continue } const perms = getBuiltinPermissionByID(role.permissionId) - const typedPermission = perms.permissions.find(perm => perm.type === type) + const typedPermission = perms.permissions.find((perm) => perm.type === type) if ( typedPermission && CURRENTLY_SUPPORTED_LEVELS.indexOf(typedPermission.level) !== -1 diff --git a/packages/server/src/utilities/usageQuota.js b/packages/server/src/utilities/usageQuota.js index d042d290d5..77844f771f 100644 --- a/packages/server/src/utilities/usageQuota.js +++ b/packages/server/src/utilities/usageQuota.js @@ -49,7 +49,7 @@ exports.Properties = { AUTOMATION: "automationRuns", } -exports.getAPIKey = async appId => { +exports.getAPIKey = async (appId) => { if (!env.USE_QUOTAS) { return { apiKey: null } } diff --git a/packages/server/src/utilities/workerRequests.js b/packages/server/src/utilities/workerRequests.js index 2de74aa155..2dea9b1a30 100644 --- a/packages/server/src/utilities/workerRequests.js +++ b/packages/server/src/utilities/workerRequests.js @@ -34,7 +34,7 @@ function request(ctx, request) { exports.request = request -exports.getDeployedApps = async ctx => { +exports.getDeployedApps = async (ctx) => { if (!env.SELF_HOSTED) { throw "Can only check apps for self hosted environments" } @@ -84,7 +84,7 @@ exports.getGlobalUsers = async (ctx, appId = null, globalId = null) => { return users } if (Array.isArray(users)) { - users = users.map(user => getAppRole(appId, user)) + users = users.map((user) => getAppRole(appId, user)) } else { users = getAppRole(appId, users) } diff --git a/packages/standard-components/scripts/deploy.js b/packages/standard-components/scripts/deploy.js index e0a63d0607..2d5cc9a778 100644 --- a/packages/standard-components/scripts/deploy.js +++ b/packages/standard-components/scripts/deploy.js @@ -36,6 +36,6 @@ run() .then(() => { console.log(`Deployment complete, version ${packageJson.version}`) }) - .catch(err => { + .catch((err) => { console.error(err) }) diff --git a/packages/standard-components/src/charts/ApexOptionsBuilder.js b/packages/standard-components/src/charts/ApexOptionsBuilder.js index 5c2ae1eb05..d1c93e99a0 100644 --- a/packages/standard-components/src/charts/ApexOptionsBuilder.js +++ b/packages/standard-components/src/charts/ApexOptionsBuilder.js @@ -1,8 +1,8 @@ export class ApexOptionsBuilder { formatters = { - ["Default"]: val => Math.round(val * 100) / 100, - ["Thousands"]: val => `${Math.round(val / 1000)}K`, - ["Millions"]: val => `${Math.round(val / 1000000)}M`, + ["Default"]: (val) => Math.round(val * 100) / 100, + ["Thousands"]: (val) => `${Math.round(val / 1000)}K`, + ["Millions"]: (val) => `${Math.round(val / 1000000)}M`, } options = { series: [], diff --git a/packages/standard-components/src/charts/index.js b/packages/standard-components/src/charts/index.js index 008aa6b64f..b1fea9ef0d 100644 --- a/packages/standard-components/src/charts/index.js +++ b/packages/standard-components/src/charts/index.js @@ -1,6 +1,6 @@ -export { default as bar } from "./BarChart.svelte" -export { default as line } from "./LineChart.svelte" -export { default as pie } from "./PieChart.svelte" -export { default as donut } from "./DonutChart.svelte" -export { default as area } from "./AreaChart.svelte" -export { default as candlestick } from "./CandleStickChart.svelte" +export { default as bar } from "./BarChart.svelte" +export { default as line } from "./LineChart.svelte" +export { default as pie } from "./PieChart.svelte" +export { default as donut } from "./DonutChart.svelte" +export { default as area } from "./AreaChart.svelte" +export { default as candlestick } from "./CandleStickChart.svelte" diff --git a/packages/standard-components/src/forms/validation.js b/packages/standard-components/src/forms/validation.js index 5b49fa0848..bef2b6e40f 100644 --- a/packages/standard-components/src/forms/validation.js +++ b/packages/standard-components/src/forms/validation.js @@ -21,11 +21,15 @@ export const createValidatorFromConstraints = (constraints, field, table) => { // Min / max number constraint if (exists(constraints.numericality?.greaterThanOrEqualTo)) { const min = constraints.numericality.greaterThanOrEqualTo - checks.push(numericalConstraint(x => x >= min, `Minimum value is ${min}`)) + checks.push( + numericalConstraint((x) => x >= min, `Minimum value is ${min}`) + ) } if (exists(constraints.numericality?.lessThanOrEqualTo)) { const max = constraints.numericality.lessThanOrEqualTo - checks.push(numericalConstraint(x => x <= max, `Maximum value is ${max}`)) + checks.push( + numericalConstraint((x) => x <= max, `Maximum value is ${max}`) + ) } // Inclusion constraint @@ -46,7 +50,7 @@ export const createValidatorFromConstraints = (constraints, field, table) => { } // Evaluate each constraint - return value => { + return (value) => { for (let check of checks) { const error = check(value) if (error) { @@ -57,9 +61,9 @@ export const createValidatorFromConstraints = (constraints, field, table) => { } } -const exists = value => value != null && value !== "" +const exists = (value) => value != null && value !== "" -const presenceConstraint = value => { +const presenceConstraint = (value) => { let invalid if (Array.isArray(value)) { invalid = value.length === 0 @@ -69,14 +73,14 @@ const presenceConstraint = value => { return invalid ? "Required" : null } -const lengthConstraint = maxLength => value => { +const lengthConstraint = (maxLength) => (value) => { if (value && value.length > maxLength) { return `Maximum ${maxLength} characters` } return null } -const numericalConstraint = (constraint, error) => value => { +const numericalConstraint = (constraint, error) => (value) => { if (isNaN(value)) { return "Must be a number" } @@ -87,7 +91,7 @@ const numericalConstraint = (constraint, error) => value => { return null } -const inclusionConstraint = (options = []) => value => { +const inclusionConstraint = (options = []) => (value) => { if (value == null || value === "") { return null } @@ -99,7 +103,7 @@ const inclusionConstraint = (options = []) => value => { const dateConstraint = (dateString, isEarliest) => { const dateLimit = Date.parse(dateString) - return value => { + return (value) => { if (value == null || value === "") { return null } diff --git a/packages/standard-components/src/helpers.js b/packages/standard-components/src/helpers.js index af98473ac9..91652b358f 100644 --- a/packages/standard-components/src/helpers.js +++ b/packages/standard-components/src/helpers.js @@ -4,7 +4,7 @@ * @param string * @returns {string} */ -export const capitalise = string => { +export const capitalise = (string) => { return string.substring(0, 1).toUpperCase() + string.substring(1) } @@ -26,7 +26,9 @@ export const cssVars = (node, props) => { delete props[key] }) - Object.keys(props).forEach(name => node.style.removeProperty(`--${name}`)) + Object.keys(props).forEach((name) => + node.style.removeProperty(`--${name}`) + ) props = new_props }, } diff --git a/packages/string-templates/scripts/gen-collection-info.js b/packages/string-templates/scripts/gen-collection-info.js index a33d967a62..8e902fe07f 100644 --- a/packages/string-templates/scripts/gen-collection-info.js +++ b/packages/string-templates/scripts/gen-collection-info.js @@ -93,8 +93,8 @@ function getCommentInfo(file, func) { docs.description = docs.description.replace(/[ ]{2,}/g, " ") docs.description = docs.description.replace(/is is/g, "is") const examples = docs.tags - .filter(el => el.title === "example") - .map(el => el.description) + .filter((el) => el.title === "example") + .map((el) => el.description) const blocks = docs.description.split("```") if (examples.length > 0) { docs.example = examples.join(" ") @@ -130,14 +130,11 @@ function run() { const fnc = entry[1].toString() const jsDocInfo = getCommentInfo(collectionFile, fnc) let args = jsDocInfo.tags - .filter(tag => tag.title === "param") + .filter((tag) => tag.title === "param") .map( - tag => + (tag) => tag.description && - tag.description - .replace(/`/g, "") - .split(" ")[0] - .trim() + tag.description.replace(/`/g, "").split(" ")[0].trim() ) collectionInfo[name] = fixSpecialCases(name, { args, diff --git a/packages/string-templates/src/helpers/Helper.js b/packages/string-templates/src/helpers/Helper.js index 8eee332678..979100d2f7 100644 --- a/packages/string-templates/src/helpers/Helper.js +++ b/packages/string-templates/src/helpers/Helper.js @@ -6,7 +6,7 @@ class Helper { register(handlebars) { // wrap the function so that no helper can cause handlebars to break - handlebars.registerHelper(this.name, value => { + handlebars.registerHelper(this.name, (value) => { return this.fn(value) || value }) } diff --git a/packages/string-templates/src/helpers/external.js b/packages/string-templates/src/helpers/external.js index 0fa7f734d0..cb3197c232 100644 --- a/packages/string-templates/src/helpers/external.js +++ b/packages/string-templates/src/helpers/external.js @@ -23,7 +23,7 @@ const ADDED_HELPERS = { duration: duration, } -exports.registerAll = handlebars => { +exports.registerAll = (handlebars) => { for (let [name, helper] of Object.entries(ADDED_HELPERS)) { handlebars.registerHelper(name, helper) } @@ -51,7 +51,7 @@ exports.registerAll = handlebars => { exports.externalHelperNames = externalNames.concat(Object.keys(ADDED_HELPERS)) } -exports.unregisterAll = handlebars => { +exports.unregisterAll = (handlebars) => { for (let name of Object.keys(ADDED_HELPERS)) { handlebars.unregisterHelper(name) } diff --git a/packages/string-templates/src/helpers/index.js b/packages/string-templates/src/helpers/index.js index 05145f7c7a..d8dc0045f1 100644 --- a/packages/string-templates/src/helpers/index.js +++ b/packages/string-templates/src/helpers/index.js @@ -14,11 +14,11 @@ const HTML_SWAPS = { const HELPERS = [ // external helpers - new Helper(HelperFunctionNames.OBJECT, value => { + new Helper(HelperFunctionNames.OBJECT, (value) => { return new SafeString(JSON.stringify(value)) }), // this help is applied to all statements - new Helper(HelperFunctionNames.ALL, value => { + new Helper(HelperFunctionNames.ALL, (value) => { // null/undefined values produce bad results if (value == null) { return "" @@ -27,12 +27,12 @@ const HELPERS = [ if (text == null || typeof text !== "string") { return text } - return text.replace(/[<>]/g, tag => { + return text.replace(/[<>]/g, (tag) => { return HTML_SWAPS[tag] || tag }) }), // adds a note for post-processor - new Helper(HelperFunctionNames.LITERAL, value => { + new Helper(HelperFunctionNames.LITERAL, (value) => { const type = typeof value const outputVal = type === "object" ? JSON.stringify(value) : value return `{{${LITERAL_MARKER} ${type}-${outputVal}}}` @@ -46,7 +46,7 @@ module.exports.HelperNames = () => { ) } -module.exports.registerAll = handlebars => { +module.exports.registerAll = (handlebars) => { for (let helper of HELPERS) { helper.register(handlebars) } @@ -54,7 +54,7 @@ module.exports.registerAll = handlebars => { externalHandlebars.registerAll(handlebars) } -module.exports.unregisterAll = handlebars => { +module.exports.unregisterAll = (handlebars) => { for (let helper of HELPERS) { helper.unregister(handlebars) } diff --git a/packages/string-templates/src/processors/index.js b/packages/string-templates/src/processors/index.js index 174041133a..c42b80fe8b 100644 --- a/packages/string-templates/src/processors/index.js +++ b/packages/string-templates/src/processors/index.js @@ -27,12 +27,12 @@ module.exports.preprocess = (string, finalise = true) => { // might want to pre-process for other benefits but still want to see errors if (!finalise) { processors = processors.filter( - processor => processor.name !== preprocessor.PreprocessorNames.FINALISE + (processor) => processor.name !== preprocessor.PreprocessorNames.FINALISE ) } return process(string, processors) } -module.exports.postprocess = string => { +module.exports.postprocess = (string) => { return process(string, postprocessor.processors) } diff --git a/packages/string-templates/src/processors/postprocessor.js b/packages/string-templates/src/processors/postprocessor.js index adc8362abe..ba2fbc9878 100644 --- a/packages/string-templates/src/processors/postprocessor.js +++ b/packages/string-templates/src/processors/postprocessor.js @@ -17,7 +17,7 @@ class Postprocessor { } module.exports.processors = [ - new Postprocessor(PostProcessorNames.CONVERT_LITERALS, statement => { + new Postprocessor(PostProcessorNames.CONVERT_LITERALS, (statement) => { if (!statement.includes(LITERAL_MARKER)) { return statement } diff --git a/packages/string-templates/src/processors/preprocessor.js b/packages/string-templates/src/processors/preprocessor.js index ee3a3a9730..02027049c5 100644 --- a/packages/string-templates/src/processors/preprocessor.js +++ b/packages/string-templates/src/processors/preprocessor.js @@ -24,7 +24,7 @@ class Preprocessor { } module.exports.processors = [ - new Preprocessor(PreprocessorNames.SWAP_TO_DOT, statement => { + new Preprocessor(PreprocessorNames.SWAP_TO_DOT, (statement) => { let startBraceIdx = statement.indexOf("[") let lastIdx = 0 while (startBraceIdx !== -1) { @@ -39,7 +39,7 @@ module.exports.processors = [ return statement }), - new Preprocessor(PreprocessorNames.FIX_FUNCTIONS, statement => { + new Preprocessor(PreprocessorNames.FIX_FUNCTIONS, (statement) => { for (let specialCase of FUNCTION_CASES) { const toFind = `{ ${specialCase}`, replacement = `{${specialCase}` @@ -48,7 +48,7 @@ module.exports.processors = [ return statement }), - new Preprocessor(PreprocessorNames.FINALISE, statement => { + new Preprocessor(PreprocessorNames.FINALISE, (statement) => { let insideStatement = statement.slice(2, statement.length - 2) if (insideStatement.charAt(0) === " ") { insideStatement = insideStatement.slice(1) @@ -63,7 +63,7 @@ module.exports.processors = [ return statement } } - if (HelperNames().some(option => option.includes(possibleHelper))) { + if (HelperNames().some((option) => option.includes(possibleHelper))) { insideStatement = `(${insideStatement})` } return `{{ all ${insideStatement} }}` diff --git a/packages/string-templates/src/utilities.js b/packages/string-templates/src/utilities.js index b33e8bfe1d..b1a9d6415c 100644 --- a/packages/string-templates/src/utilities.js +++ b/packages/string-templates/src/utilities.js @@ -3,7 +3,7 @@ const ALPHA_NUMERIC_REGEX = /^[A-Za-z0-9]+$/g module.exports.FIND_HBS_REGEX = /{{([^{].*?)}}/g -module.exports.isAlphaNumeric = char => { +module.exports.isAlphaNumeric = (char) => { return char.match(ALPHA_NUMERIC_REGEX) } @@ -12,11 +12,8 @@ module.exports.swapStrings = (string, start, length, swap) => { } // removes null and undefined -module.exports.removeNull = obj => { - obj = _(obj) - .omitBy(_.isUndefined) - .omitBy(_.isNull) - .value() +module.exports.removeNull = (obj) => { + obj = _(obj).omitBy(_.isUndefined).omitBy(_.isNull).value() for (let [key, value] of Object.entries(obj)) { // only objects if (typeof value === "object" && !Array.isArray(value)) { @@ -26,14 +23,14 @@ module.exports.removeNull = obj => { return obj } -module.exports.addConstants = obj => { +module.exports.addConstants = (obj) => { if (obj.now == null) { obj.now = new Date() } return obj } -module.exports.removeHandlebarsStatements = string => { +module.exports.removeHandlebarsStatements = (string) => { let regexp = new RegExp(exports.FIND_HBS_REGEX) let matches = string.match(regexp) if (matches == null) { diff --git a/packages/worker/scripts/dev/manage.js b/packages/worker/scripts/dev/manage.js index f363bd05ac..a3d545b4a1 100644 --- a/packages/worker/scripts/dev/manage.js +++ b/packages/worker/scripts/dev/manage.js @@ -16,7 +16,7 @@ async function init() { COUCH_DB_URL: "http://budibase:budibase@localhost:10000/db/", } let envFile = "" - Object.keys(envFileJson).forEach(key => { + Object.keys(envFileJson).forEach((key) => { envFile += `${key}=${envFileJson[key]}\n` }) fs.writeFileSync(envFilePath, envFile) @@ -32,7 +32,7 @@ command() .then(() => { console.log("Done! 🎉") }) - .catch(err => { + .catch((err) => { console.error( "Something went wrong while managing budibase dev worker:", err.message diff --git a/packages/worker/src/api/controllers/admin/configs.js b/packages/worker/src/api/controllers/admin/configs.js index 107c0c8fa8..6a84b299f0 100644 --- a/packages/worker/src/api/controllers/admin/configs.js +++ b/packages/worker/src/api/controllers/admin/configs.js @@ -10,7 +10,7 @@ const email = require("../../../utilities/email") const GLOBAL_DB = StaticDatabases.GLOBAL.name -exports.save = async function(ctx) { +exports.save = async function (ctx) { const db = new CouchDB(GLOBAL_DB) const { type, config } = ctx.request.body const { group, user } = config @@ -45,28 +45,28 @@ exports.save = async function(ctx) { } } -exports.fetch = async function(ctx) { +exports.fetch = async function (ctx) { const db = new CouchDB(GLOBAL_DB) const response = await db.allDocs( getConfigParams(undefined, { include_docs: true, }) ) - ctx.body = response.rows.map(row => row.doc) + ctx.body = response.rows.map((row) => row.doc) } /** * Gets the most granular config for a particular configuration type. * The hierarchy is type -> group -> user. */ -exports.find = async function(ctx) { +exports.find = async function (ctx) { const db = new CouchDB(GLOBAL_DB) const userId = ctx.params.user && ctx.params.user._id const { group } = ctx.query if (group) { const group = await db.get(group) - const userInGroup = group.users.some(groupUser => groupUser === userId) + const userInGroup = group.users.some((groupUser) => groupUser === userId) if (!ctx.user.admin && !userInGroup) { ctx.throw(400, `User is not in specified group: ${group}.`) } @@ -90,7 +90,7 @@ exports.find = async function(ctx) { } } -exports.destroy = async function(ctx) { +exports.destroy = async function (ctx) { const db = new CouchDB(GLOBAL_DB) const { id, rev } = ctx.params diff --git a/packages/worker/src/api/controllers/admin/email.js b/packages/worker/src/api/controllers/admin/email.js index 9f4060d20f..dfb0d5b461 100644 --- a/packages/worker/src/api/controllers/admin/email.js +++ b/packages/worker/src/api/controllers/admin/email.js @@ -53,7 +53,7 @@ async function buildEmail(purpose, email, user) { }) } -exports.sendEmail = async ctx => { +exports.sendEmail = async (ctx) => { const { groupId, email, userId, purpose } = ctx.request.body const db = new CouchDB(GLOBAL_DB) const params = {} diff --git a/packages/worker/src/api/controllers/admin/groups.js b/packages/worker/src/api/controllers/admin/groups.js index baa510f487..6abc986394 100644 --- a/packages/worker/src/api/controllers/admin/groups.js +++ b/packages/worker/src/api/controllers/admin/groups.js @@ -7,7 +7,7 @@ const { const GLOBAL_DB = StaticDatabases.GLOBAL.name -exports.save = async function(ctx) { +exports.save = async function (ctx) { const db = new CouchDB(GLOBAL_DB) const groupDoc = ctx.request.body @@ -27,17 +27,17 @@ exports.save = async function(ctx) { } } -exports.fetch = async function(ctx) { +exports.fetch = async function (ctx) { const db = new CouchDB(GLOBAL_DB) const response = await db.allDocs( getGroupParams(undefined, { include_docs: true, }) ) - ctx.body = response.rows.map(row => row.doc) + ctx.body = response.rows.map((row) => row.doc) } -exports.find = async function(ctx) { +exports.find = async function (ctx) { const db = new CouchDB(GLOBAL_DB) try { ctx.body = await db.get(ctx.params.id) @@ -46,7 +46,7 @@ exports.find = async function(ctx) { } } -exports.destroy = async function(ctx) { +exports.destroy = async function (ctx) { const db = new CouchDB(GLOBAL_DB) const { id, rev } = ctx.params diff --git a/packages/worker/src/api/controllers/admin/templates.js b/packages/worker/src/api/controllers/admin/templates.js index 30c90d50bf..0a3f2fa487 100644 --- a/packages/worker/src/api/controllers/admin/templates.js +++ b/packages/worker/src/api/controllers/admin/templates.js @@ -9,7 +9,7 @@ const { getTemplates } = require("../../../constants/templates") const GLOBAL_DB = StaticDatabases.GLOBAL.name -exports.save = async ctx => { +exports.save = async (ctx) => { const db = new CouchDB(GLOBAL_DB) const type = ctx.params.type let template = ctx.request.body @@ -30,36 +30,36 @@ exports.save = async ctx => { } } -exports.definitions = async ctx => { +exports.definitions = async (ctx) => { ctx.body = { purpose: TemplateMetadata, bindings: Object.values(TemplateBindings), } } -exports.fetch = async ctx => { +exports.fetch = async (ctx) => { ctx.body = await getTemplates() } -exports.fetchByType = async ctx => { +exports.fetchByType = async (ctx) => { ctx.body = await getTemplates({ type: ctx.params.type, }) } -exports.fetchByOwner = async ctx => { +exports.fetchByOwner = async (ctx) => { ctx.body = await getTemplates({ ownerId: ctx.params.ownerId, }) } -exports.find = async ctx => { +exports.find = async (ctx) => { ctx.body = await getTemplates({ id: ctx.params.id, }) } -exports.destroy = async ctx => { +exports.destroy = async (ctx) => { const db = new CouchDB(GLOBAL_DB) await db.remove(ctx.params.id, ctx.params.rev) ctx.message = `Template ${ctx.params.id} deleted.` diff --git a/packages/worker/src/api/controllers/admin/users.js b/packages/worker/src/api/controllers/admin/users.js index 146373e671..bcb159b618 100644 --- a/packages/worker/src/api/controllers/admin/users.js +++ b/packages/worker/src/api/controllers/admin/users.js @@ -11,7 +11,7 @@ const FIRST_USER_EMAIL = "test@test.com" const FIRST_USER_PASSWORD = "test" const GLOBAL_DB = StaticDatabases.GLOBAL.name -exports.save = async ctx => { +exports.save = async (ctx) => { const db = new CouchDB(GLOBAL_DB) const { email, password, _id } = ctx.request.body @@ -60,7 +60,7 @@ exports.save = async ctx => { } } -exports.firstUser = async ctx => { +exports.firstUser = async (ctx) => { ctx.request.body = { email: FIRST_USER_EMAIL, password: FIRST_USER_PASSWORD, @@ -72,7 +72,7 @@ exports.firstUser = async ctx => { await exports.save(ctx) } -exports.destroy = async ctx => { +exports.destroy = async (ctx) => { const db = new CouchDB(GLOBAL_DB) const dbUser = await db.get(ctx.params.id) await db.remove(dbUser._id, dbUser._rev) @@ -82,14 +82,14 @@ exports.destroy = async ctx => { } // called internally by app server user fetch -exports.fetch = async ctx => { +exports.fetch = async (ctx) => { const db = new CouchDB(GLOBAL_DB) const response = await db.allDocs( getGlobalUserParams(null, { include_docs: true, }) ) - const users = response.rows.map(row => row.doc) + const users = response.rows.map((row) => row.doc) // user hashed password shouldn't ever be returned for (let user of users) { if (user) { @@ -100,7 +100,7 @@ exports.fetch = async ctx => { } // called internally by app server user find -exports.find = async ctx => { +exports.find = async (ctx) => { const db = new CouchDB(GLOBAL_DB) let user try { diff --git a/packages/worker/src/api/controllers/app.js b/packages/worker/src/api/controllers/app.js index bed3b55942..8c96ccdfbc 100644 --- a/packages/worker/src/api/controllers/app.js +++ b/packages/worker/src/api/controllers/app.js @@ -5,7 +5,7 @@ const env = require("../../environment") const APP_PREFIX = "app_" const URL_REGEX_SLASH = /\/|\\/g -exports.getApps = async ctx => { +exports.getApps = async (ctx) => { let allDbs // allDbs call of CouchDB is very inaccurate in production if (env.COUCH_DB_URL) { @@ -13,8 +13,8 @@ exports.getApps = async ctx => { } else { allDbs = await CouchDB.allDbs() } - const appDbNames = allDbs.filter(dbName => dbName.startsWith(APP_PREFIX)) - const appPromises = appDbNames.map(db => new CouchDB(db).get(db)) + const appDbNames = allDbs.filter((dbName) => dbName.startsWith(APP_PREFIX)) + const appPromises = appDbNames.map((db) => new CouchDB(db).get(db)) const apps = await Promise.allSettled(appPromises) const body = {} diff --git a/packages/worker/src/api/controllers/auth.js b/packages/worker/src/api/controllers/auth.js index bcda523a93..58e277f6a2 100644 --- a/packages/worker/src/api/controllers/auth.js +++ b/packages/worker/src/api/controllers/auth.js @@ -34,7 +34,7 @@ exports.authenticate = async (ctx, next) => { })(ctx, next) } -exports.logout = async ctx => { +exports.logout = async (ctx) => { clearCookie(ctx, Cookies.Auth) ctx.body = { message: "User logged out" } } diff --git a/packages/worker/src/api/index.js b/packages/worker/src/api/index.js index d0e60ffcd2..fe8609de7e 100644 --- a/packages/worker/src/api/index.js +++ b/packages/worker/src/api/index.js @@ -26,7 +26,7 @@ router br: false, }) ) - .use("/health", ctx => (ctx.status = 200)) + .use("/health", (ctx) => (ctx.status = 200)) .use(buildAuthMiddleware(NO_AUTH_ENDPOINTS)) // for now no public access is allowed to worker (bar health check) .use((ctx, next) => { @@ -50,7 +50,7 @@ router.use(async (ctx, next) => { } }) -router.get("/health", ctx => (ctx.status = 200)) +router.get("/health", (ctx) => (ctx.status = 200)) // authenticated routes for (let route of routes) { diff --git a/packages/worker/src/constants/templates/index.js b/packages/worker/src/constants/templates/index.js index 23e5508341..18904bb8df 100644 --- a/packages/worker/src/constants/templates/index.js +++ b/packages/worker/src/constants/templates/index.js @@ -35,7 +35,7 @@ exports.addBaseTemplates = (templates, type = null) => { } for (let purpose of purposeList) { // check if a template exists already for purpose - if (templates.find(template => template.purpose === purpose)) { + if (templates.find((template) => template.purpose === purpose)) { continue } if (exports.EmailTemplates[purpose]) { @@ -56,18 +56,18 @@ exports.getTemplates = async ({ ownerId, type, id } = {}) => { include_docs: true, }) ) - let templates = response.rows.map(row => row.doc) + let templates = response.rows.map((row) => row.doc) // should only be one template with ID if (id) { return templates[0] } if (type) { - templates = templates.filter(template => template.type === type) + templates = templates.filter((template) => template.type === type) } return exports.addBaseTemplates(templates, type) } exports.getTemplateByPurpose = async (type, purpose) => { const templates = await exports.getTemplates({ type }) - return templates.find(template => template.purpose === purpose) + return templates.find((template) => template.purpose === purpose) } diff --git a/packages/worker/src/index.js b/packages/worker/src/index.js index 8b67181fcc..c80d27ddae 100644 --- a/packages/worker/src/index.js +++ b/packages/worker/src/index.js @@ -44,7 +44,7 @@ module.exports = server.listen(parseInt(env.PORT || 4002), async () => { console.log(`Worker running on ${JSON.stringify(server.address())}`) }) -process.on("uncaughtException", err => { +process.on("uncaughtException", (err) => { console.error(err) server.close() server.destroy() diff --git a/packages/worker/src/middleware/joi-validator.js b/packages/worker/src/middleware/joi-validator.js index 1686b0e727..8e5feab255 100644 --- a/packages/worker/src/middleware/joi-validator.js +++ b/packages/worker/src/middleware/joi-validator.js @@ -19,10 +19,10 @@ function validate(schema, property) { } } -module.exports.body = schema => { +module.exports.body = (schema) => { return validate(schema, "body") } -module.exports.params = schema => { +module.exports.params = (schema) => { return validate(schema, "params") } diff --git a/packages/worker/src/utilities/email.js b/packages/worker/src/utilities/email.js index b5e64a2793..3a17b2bfd1 100644 --- a/packages/worker/src/utilities/email.js +++ b/packages/worker/src/utilities/email.js @@ -1,6 +1,6 @@ const nodemailer = require("nodemailer") -exports.createSMTPTransport = config => { +exports.createSMTPTransport = (config) => { const options = { port: config.port, host: config.host, @@ -15,7 +15,7 @@ exports.createSMTPTransport = config => { return nodemailer.createTransport(options) } -exports.verifyConfig = async config => { +exports.verifyConfig = async (config) => { const transport = exports.createSMTPTransport(config) await transport.verify() } diff --git a/packages/worker/src/utilities/fileSystem.js b/packages/worker/src/utilities/fileSystem.js index 8f0bc8d3ed..6bb44fa4ac 100644 --- a/packages/worker/src/utilities/fileSystem.js +++ b/packages/worker/src/utilities/fileSystem.js @@ -1,5 +1,5 @@ const { readFileSync } = require("fs") -exports.readStaticFile = path => { +exports.readStaticFile = (path) => { return readFileSync(path, "utf-8") } diff --git a/packages/worker/src/utilities/index.js b/packages/worker/src/utilities/index.js index b402a82cf3..4ad800cc58 100644 --- a/packages/worker/src/utilities/index.js +++ b/packages/worker/src/utilities/index.js @@ -4,6 +4,6 @@ * @param {string} url The URL to test and remove any extra double slashes. * @return {string} The updated url. */ -exports.checkSlashesInUrl = url => { +exports.checkSlashesInUrl = (url) => { return url.replace(/(https?:\/\/)|(\/)+/g, "$1$2") } diff --git a/packages/worker/src/utilities/templates.js b/packages/worker/src/utilities/templates.js index 3035dc2bbc..4000ed5365 100644 --- a/packages/worker/src/utilities/templates.js +++ b/packages/worker/src/utilities/templates.js @@ -14,7 +14,7 @@ exports.getSettingsTemplateContext = async () => { include_docs: true, }) ) - let settings = response.rows.map(row => row.doc)[0] || {} + let settings = response.rows.map((row) => row.doc)[0] || {} if (!settings.platformUrl) { settings.platformUrl = LOCAL_URL }