Browse Source

feat: edit base

Signed-off-by: mertmit <mertmit99@gmail.com>
pull/3573/head
mertmit 2 years ago
parent
commit
5d4a3ab271
  1. 6
      packages/nc-gui/components/dashboard/settings/DataSources.vue
  2. 6
      packages/nc-gui/components/dashboard/settings/Erd.vue
  3. 6
      packages/nc-gui/components/dashboard/settings/Metadata.vue
  4. 7
      packages/nc-gui/components/dashboard/settings/Modal.vue
  5. 6
      packages/nc-gui/components/dashboard/settings/UIAcl.vue
  6. 11
      packages/nc-gui/components/dashboard/settings/data-sources/CreateBase.vue
  7. 609
      packages/nc-gui/components/dashboard/settings/data-sources/EditBase.vue
  8. 28
      packages/nocodb/src/lib/meta/api/baseApis.ts
  9. 62
      packages/nocodb/src/lib/models/Base.ts

6
packages/nc-gui/components/dashboard/settings/DataSources.vue

@ -2,6 +2,7 @@
import { Empty } from 'ant-design-vue' import { Empty } from 'ant-design-vue'
import type { BaseType } from 'nocodb-sdk' import type { BaseType } from 'nocodb-sdk'
import CreateBase from './data-sources/CreateBase.vue' import CreateBase from './data-sources/CreateBase.vue'
import EditBase from './data-sources/EditBase.vue'
import Metadata from './Metadata.vue' import Metadata from './Metadata.vue'
import UIAcl from './UIAcl.vue' import UIAcl from './UIAcl.vue'
import Erd from './Erd.vue' import Erd from './Erd.vue'
@ -147,7 +148,7 @@ watch(
</a-table> </a-table>
</div> </div>
<div v-else-if="props.state === DataSourcesSubTab.New" class="max-h-600px overflow-y-auto"> <div v-else-if="props.state === DataSourcesSubTab.New" class="max-h-600px overflow-y-auto">
<CreateBase /> <CreateBase @base-created="loadBases" />
</div> </div>
<div v-else-if="props.state === DataSourcesSubTab.Metadata" class="max-h-600px overflow-y-auto"> <div v-else-if="props.state === DataSourcesSubTab.Metadata" class="max-h-600px overflow-y-auto">
<Metadata :base-id="activeBaseId" /> <Metadata :base-id="activeBaseId" />
@ -158,6 +159,9 @@ watch(
<div v-else-if="props.state === DataSourcesSubTab.ERD" class="max-h-600px overflow-y-auto"> <div v-else-if="props.state === DataSourcesSubTab.ERD" class="max-h-600px overflow-y-auto">
<Erd :base-id="activeBaseId" /> <Erd :base-id="activeBaseId" />
</div> </div>
<div v-else-if="props.state === DataSourcesSubTab.Edit" class="max-h-600px overflow-y-auto">
<EditBase :base-id="activeBaseId" @base-updated="loadBases" />
</div>
</div> </div>
</div> </div>
</template> </template>

6
packages/nc-gui/components/dashboard/settings/Erd.vue

@ -1,9 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
interface Props { const props = defineProps<{
baseId: string baseId: string
} }>()
const props = defineProps<Props>()
</script> </script>
<template> <template>

6
packages/nc-gui/components/dashboard/settings/Metadata.vue

@ -1,11 +1,9 @@
<script setup lang="ts"> <script setup lang="ts">
import { Empty, extractSdkResponseErrorMsg, h, message, useI18n, useNuxtApp, useProject } from '#imports' import { Empty, extractSdkResponseErrorMsg, h, message, useI18n, useNuxtApp, useProject } from '#imports'
interface Props { const props = defineProps<{
baseId: string baseId: string
} }>()
const props = defineProps<Props>()
const { $api } = useNuxtApp() const { $api } = useNuxtApp()

7
packages/nc-gui/components/dashboard/settings/Modal.vue

@ -161,6 +161,13 @@ watch(
}, },
) )
watch(
() => props.dataSourcesState,
(nextState) => {
dataSourcesState.value = nextState || ''
},
)
watch( watch(
() => props.modelValue, () => props.modelValue,
() => { () => {

6
packages/nc-gui/components/dashboard/settings/UIAcl.vue

@ -13,11 +13,9 @@ import {
viewIcons, viewIcons,
} from '#imports' } from '#imports'
interface Props { const props = defineProps<{
baseId: string baseId: string
} }>()
const props = defineProps<Props>()
const { t } = useI18n() const { t } = useI18n()

11
packages/nc-gui/components/dashboard/settings/data-sources/CreateBase.vue

@ -25,6 +25,8 @@ import { ClientType } from '~/lib'
import { DefaultConnection, SQLiteConnection } from '~/utils' import { DefaultConnection, SQLiteConnection } from '~/utils'
import type { ProjectCreateForm } from '~/utils' import type { ProjectCreateForm } from '~/utils'
const emit = defineEmits(['baseCreated'])
const { project, loadProject } = useProject() const { project, loadProject } = useProject()
const useForm = Form.useForm const useForm = Form.useForm
@ -39,6 +41,8 @@ const { $e } = useNuxtApp()
const { t } = useI18n() const { t } = useI18n()
const toggleDialog = inject(ToggleDialogInj, () => {})
let formState = $ref<ProjectCreateForm>({ let formState = $ref<ProjectCreateForm>({
title: '', title: '',
dataSource: { ...getDefaultConnectionConfig(ClientType.MYSQL) }, dataSource: { ...getDefaultConnectionConfig(ClientType.MYSQL) },
@ -217,6 +221,9 @@ const createBase = async () => {
$e('a:base:create:extdb') $e('a:base:create:extdb')
await loadProject() await loadProject()
emit('baseCreated')
message.success('Base created!')
toggleDialog(true, 'dataSources', '')
} catch (e: any) { } catch (e: any) {
message.error(await extractSdkResponseErrorMsg(e)) message.error(await extractSdkResponseErrorMsg(e))
} }
@ -313,8 +320,8 @@ watch(
) )
// select and focus title field on load // select and focus title field on load
onMounted(() => { onMounted(async () => {
formState.title = generateUniqueName() formState.title = await generateUniqueName()
nextTick(() => { nextTick(() => {
// todo: replace setTimeout and follow better approach // todo: replace setTimeout and follow better approach
setTimeout(() => { setTimeout(() => {

609
packages/nc-gui/components/dashboard/settings/data-sources/EditBase.vue

@ -0,0 +1,609 @@
<script lang="ts" setup>
import type { BaseType } from 'nocodb-sdk'
import { Form, Modal, message } from 'ant-design-vue'
import type { SelectHandler } from 'ant-design-vue/es/vc-select/Select'
import {
CertTypes,
SSLUsage,
clientTypes,
computed,
extractSdkResponseErrorMsg,
fieldRequiredValidator,
getDefaultConnectionConfig,
getTestDatabaseName,
onMounted,
projectTitleValidator,
readFile,
ref,
useApi,
useI18n,
useNuxtApp,
watch,
} from '#imports'
import { ClientType } from '~/lib'
import { DefaultConnection, SQLiteConnection } from '~/utils'
import type { ProjectCreateForm } from '~/utils'
const props = defineProps<{
baseId: string
}>()
const emit = defineEmits(['baseUpdated'])
const { project, loadProject } = useProject()
const useForm = Form.useForm
const testSuccess = ref(false)
const form = ref<typeof Form>()
const { api } = useApi()
const { $e } = useNuxtApp()
const { t } = useI18n()
const toggleDialog = inject(ToggleDialogInj, () => {})
const formState = ref<ProjectCreateForm>({
title: '',
dataSource: { ...getDefaultConnectionConfig(ClientType.MYSQL) },
inflection: {
inflectionColumn: 'camelize',
inflectionTable: 'camelize',
},
sslUse: SSLUsage.No,
extraParameters: [],
})
const customFormState = ref<ProjectCreateForm>({
title: '',
dataSource: { ...getDefaultConnectionConfig(ClientType.MYSQL) },
inflection: {
inflectionColumn: 'camelize',
inflectionTable: 'camelize',
},
sslUse: SSLUsage.No,
extraParameters: [],
})
const validators = computed(() => {
return {
'title': [
{
required: true,
message: 'Base name is required',
},
projectTitleValidator,
],
'extraParameters': [extraParameterValidator],
'dataSource.client': [fieldRequiredValidator()],
...(formState.value.dataSource.client === ClientType.SQLITE
? {
'dataSource.connection.connection.filename': [fieldRequiredValidator()],
}
: {
'dataSource.connection.host': [fieldRequiredValidator()],
'dataSource.connection.port': [fieldRequiredValidator()],
'dataSource.connection.user': [fieldRequiredValidator()],
'dataSource.connection.password': [fieldRequiredValidator()],
'dataSource.connection.database': [fieldRequiredValidator()],
...([ClientType.PG, ClientType.MSSQL].includes(formState.value.dataSource.client)
? {
'dataSource.searchPath.0': [fieldRequiredValidator()],
}
: {}),
}),
}
})
const { validate, validateInfos } = useForm(formState, validators)
const onClientChange = () => {
formState.value.dataSource = { ...getDefaultConnectionConfig(formState.value.dataSource.client) }
}
const onSSLModeChange = ((mode: SSLUsage) => {
if (formState.value.dataSource.client !== ClientType.SQLITE) {
const connection = formState.value.dataSource.connection as DefaultConnection
switch (mode) {
case SSLUsage.No:
delete connection.ssl
break
case SSLUsage.Allowed:
connection.ssl = 'true'
break
default:
connection.ssl = {
ca: '',
cert: '',
key: '',
}
break
}
}
}) as SelectHandler
const updateSSLUse = () => {
if (formState.value.dataSource.client !== ClientType.SQLITE) {
const connection = formState.value.dataSource.connection as DefaultConnection
if (connection.ssl) {
if (typeof connection.ssl === 'string') {
formState.value.sslUse = SSLUsage.Allowed
} else {
formState.value.sslUse = SSLUsage.Preferred
}
} else {
formState.value.sslUse = SSLUsage.No
}
}
}
const addNewParam = () => {
formState.value.extraParameters.push({ key: '', value: '' })
}
const removeParam = (index: number) => {
formState.value.extraParameters.splice(index, 1)
}
const inflectionTypes = ['camelize', 'none']
const importURL = ref('')
const configEditDlg = ref(false)
const importURLDlg = ref(false)
const caFileInput = ref<HTMLInputElement>()
const keyFileInput = ref<HTMLInputElement>()
const certFileInput = ref<HTMLInputElement>()
const onFileSelect = (key: CertTypes, el?: HTMLInputElement) => {
if (!el) return
readFile(el, (content) => {
if ('ssl' in formState.value.dataSource.connection && typeof formState.value.dataSource.connection.ssl === 'object')
formState.value.dataSource.connection.ssl[key] = content ?? ''
})
}
const sslFilesRequired = computed(
() => !!formState.value.sslUse && formState.value.sslUse !== SSLUsage.No && formState.value.sslUse !== SSLUsage.Allowed,
)
function getConnectionConfig() {
const extraParameters = Object.fromEntries(new Map(formState.value.extraParameters.map((object) => [object.key, object.value])))
const connection = {
...formState.value.dataSource.connection,
...extraParameters,
}
if ('ssl' in connection && connection.ssl) {
if (
formState.value.sslUse === SSLUsage.No ||
(typeof connection.ssl === 'object' && Object.values(connection.ssl).every((v) => v === null || v === undefined))
) {
delete connection.ssl
}
}
return connection
}
const focusInvalidInput = () => {
form.value?.$el.querySelector('.ant-form-item-explain-error')?.parentNode?.parentNode?.querySelector('input')?.focus()
}
const editBase = async () => {
try {
await validate()
} catch (e) {
focusInvalidInput()
return
}
try {
if (!project.value?.id) return
const connection = getConnectionConfig()
const config = { ...formState.value.dataSource, connection }
await api.base.update(project.value?.id, props.baseId, {
alias: formState.value.title,
type: formState.value.dataSource.client,
config,
inflection_column: formState.value.inflection.inflectionColumn,
inflection_table: formState.value.inflection.inflectionTable,
})
$e('a:base:edit:extdb')
await loadProject()
emit('baseUpdated')
message.success('Base updated!')
toggleDialog(true, 'dataSources', '')
} catch (e: any) {
message.error(await extractSdkResponseErrorMsg(e))
}
}
const testConnection = async () => {
try {
await validate()
} catch (e) {
focusInvalidInput()
return
}
$e('a:base:edit:extdb:test-connection', [])
try {
if (formState.value.dataSource.client === ClientType.SQLITE) {
testSuccess.value = true
} else {
const connection = getConnectionConfig()
connection.database = getTestDatabaseName(formState.value.dataSource)!
const testConnectionConfig = {
...formState.value.dataSource,
connection,
}
const result = await api.utils.testConnection(testConnectionConfig)
if (result.code === 0) {
testSuccess.value = true
Modal.confirm({
title: t('msg.info.dbConnected'),
icon: null,
type: 'success',
okText: 'Ok & Edit Base',
okType: 'primary',
cancelText: t('general.cancel'),
onOk: editBase,
})
} else {
testSuccess.value = false
message.error(`${t('msg.error.dbConnectionFailed')} ${result.message}`)
}
}
} catch (e: any) {
testSuccess.value = false
message.error(await extractSdkResponseErrorMsg(e))
}
}
const handleImportURL = async () => {
if (!importURL.value || importURL.value === '') return
const connectionConfig = await api.utils.urlToConfig({ url: importURL.value })
if (connectionConfig) {
formState.value.dataSource.client = connectionConfig.client
formState.value.dataSource.connection = { ...connectionConfig.connection }
} else {
message.error(t('msg.error.invalidURL'))
}
importURLDlg.value = false
updateSSLUse()
}
const handleEditJSON = () => {
customFormState.value = formState.value
configEditDlg.value = true
}
const handleOk = () => {
formState.value = customFormState.value
configEditDlg.value = false
updateSSLUse()
}
// reset test status on config change
watch(
() => formState.value.dataSource,
() => (testSuccess.value = false),
{ deep: true },
)
// load base config
onMounted(async () => {
if (project.value?.id) {
const definedParameters = ['host', 'port', 'user', 'password', 'database']
const activeBase = (await api.base.read(project.value?.id, props.baseId)) as BaseType
const tempParameters = Object.entries(activeBase.config.connection)
.filter(([key]) => !definedParameters.includes(key))
.map(([key, value]) => ({ key: key as string, value: value as string }))
formState.value = {
title: activeBase.alias || '',
dataSource: activeBase.config,
inflection: {
inflectionColumn: activeBase.inflection_column,
inflectionTable: activeBase.inflection_table,
},
extraParameters: tempParameters,
sslUse: SSLUsage.No,
}
updateSSLUse()
}
})
</script>
<template>
<div
class="create-external bg-white relative flex flex-col justify-center gap-2 w-full p-8 md:(rounded-lg border-1 border-gray-200 shadow-xl)"
>
<h1 class="prose-2xl font-bold self-center my-4">Edit Base</h1>
<a-form
ref="form"
:model="formState"
name="external-project-create-form"
layout="horizontal"
no-style
:label-col="{ span: 8 }"
>
<a-form-item label="Base Name" v-bind="validateInfos.title">
<a-input v-model:value="formState.title" class="nc-extdb-proj-name" />
</a-form-item>
<a-form-item :label="$t('labels.dbType')" v-bind="validateInfos['dataSource.client']">
<a-select
v-model:value="formState.dataSource.client"
class="nc-extdb-db-type"
dropdown-class-name="nc-dropdown-ext-db-type"
@change="onClientChange"
>
<a-select-option v-for="client in clientTypes" :key="client.value" :value="client.value"
>{{ client.text }}
</a-select-option>
</a-select>
</a-form-item>
<!-- SQLite File -->
<a-form-item
v-if="formState.dataSource.client === ClientType.SQLITE"
:label="$t('labels.sqliteFile')"
v-bind="validateInfos['dataSource.connection.connection.filename']"
>
<a-input v-model:value="(formState.dataSource.connection as SQLiteConnection).connection.filename" />
</a-form-item>
<template v-else>
<!-- Host Address -->
<a-form-item :label="$t('labels.hostAddress')" v-bind="validateInfos['dataSource.connection.host']">
<a-input v-model:value="(formState.dataSource.connection as DefaultConnection).host" class="nc-extdb-host-address" />
</a-form-item>
<!-- Port Number -->
<a-form-item :label="$t('labels.port')" v-bind="validateInfos['dataSource.connection.port']">
<a-input-number
v-model:value="(formState.dataSource.connection as DefaultConnection).port"
class="!w-full nc-extdb-host-port"
/>
</a-form-item>
<!-- Username -->
<a-form-item :label="$t('labels.username')" v-bind="validateInfos['dataSource.connection.user']">
<a-input v-model:value="(formState.dataSource.connection as DefaultConnection).user" class="nc-extdb-host-user" />
</a-form-item>
<!-- Password -->
<a-form-item :label="$t('labels.password')">
<a-input-password
v-model:value="(formState.dataSource.connection as DefaultConnection).password"
class="nc-extdb-host-password"
/>
</a-form-item>
<!-- Database -->
<a-form-item :label="$t('labels.database')" v-bind="validateInfos['dataSource.connection.database']">
<!-- Database : create if not exists -->
<a-input
v-model:value="formState.dataSource.connection.database"
:placeholder="$t('labels.dbCreateIfNotExists')"
class="nc-extdb-host-database"
/>
</a-form-item>
<!-- Schema name -->
<a-form-item
v-if="[ClientType.MSSQL, ClientType.PG].includes(formState.dataSource.client) && formState.dataSource.searchPath"
:label="$t('labels.schemaName')"
v-bind="validateInfos['dataSource.searchPath.0']"
>
<a-input v-model:value="formState.dataSource.searchPath[0]" />
</a-form-item>
<a-collapse ghost expand-icon-position="right" class="!mt-6">
<a-collapse-panel key="1">
<template #header>
<div class="flex items-center gap-2">
<!-- Use Connection URL -->
<a-button type="default" class="nc-extdb-btn-import-url" @click.stop="importURLDlg = true">
{{ $t('activity.useConnectionUrl') }}
</a-button>
<span>{{ $t('title.advancedParameters') }}</span>
</div>
</template>
<a-form-item label="SSL mode">
<a-select v-model:value="formState.sslUse" dropdown-class-name="nc-dropdown-ssl-mode" @select="onSSLModeChange">
<a-select-option v-for="opt in Object.values(SSLUsage)" :key="opt" :value="opt">{{ opt }}</a-select-option>
</a-select>
</a-form-item>
<a-form-item label="SSL keys">
<div class="flex gap-2">
<a-tooltip placement="top">
<!-- Select .cert file -->
<template #title>
<span>{{ $t('tooltip.clientCert') }}</span>
</template>
<a-button :disabled="!sslFilesRequired" class="shadow" @click="certFileInput?.click()">
{{ $t('labels.clientCert') }}
</a-button>
</a-tooltip>
<a-tooltip placement="top">
<!-- Select .key file -->
<template #title>
<span>{{ $t('tooltip.clientKey') }}</span>
</template>
<a-button :disabled="!sslFilesRequired" class="shadow" @click="keyFileInput?.click()">
{{ $t('labels.clientKey') }}
</a-button>
</a-tooltip>
<a-tooltip placement="top">
<!-- Select CA file -->
<template #title>
<span>{{ $t('tooltip.clientCA') }}</span>
</template>
<a-button :disabled="!sslFilesRequired" class="shadow" @click="caFileInput?.click()">
{{ $t('labels.serverCA') }}
</a-button>
</a-tooltip>
</div>
</a-form-item>
<input ref="caFileInput" type="file" class="!hidden" @change="onFileSelect(CertTypes.ca, caFileInput)" />
<input ref="certFileInput" type="file" class="!hidden" @change="onFileSelect(CertTypes.cert, certFileInput)" />
<input ref="keyFileInput" type="file" class="!hidden" @change="onFileSelect(CertTypes.key, keyFileInput)" />
<a-divider />
<!-- Extra connection parameters -->
<a-form-item class="mb-2" :label="$t('labels.extraConnectionParameters')" v-bind="validateInfos.extraParameters">
<a-card>
<div v-for="(item, index) of formState.extraParameters" :key="index">
<div class="flex py-1 items-center gap-1">
<a-input v-model:value="item.key" />
<span>:</span>
<a-input v-model:value="item.value" />
<MdiClose :style="{ 'font-size': '1.5em', 'color': 'red' }" @click="removeParam(index)" />
</div>
</div>
<a-button type="dashed" class="w-full caption mt-2" @click="addNewParam">
<div class="flex items-center justify-center"><MdiPlus /></div>
</a-button>
</a-card>
</a-form-item>
<a-divider />
<a-form-item :label="$t('labels.inflection.tableName')">
<a-select
v-model:value="formState.inflection.inflectionTable"
dropdown-class-name="nc-dropdown-inflection-table-name"
>
<a-select-option v-for="type in inflectionTypes" :key="type" :value="type">{{ type }}</a-select-option>
</a-select>
</a-form-item>
<a-form-item :label="$t('labels.inflection.columnName')">
<a-select
v-model:value="formState.inflection.inflectionColumn"
dropdown-class-name="nc-dropdown-inflection-column-name"
>
<a-select-option v-for="type in inflectionTypes" :key="type" :value="type">{{ type }}</a-select-option>
</a-select>
</a-form-item>
<div class="flex justify-end">
<a-button class="!shadow-md" @click="handleEditJSON()">
<!-- Edit connection JSON -->
{{ $t('activity.editConnJson') }}
</a-button>
</div>
</a-collapse-panel>
</a-collapse>
</template>
<a-form-item class="flex justify-center !mt-5">
<div class="flex justify-center gap-2">
<a-button type="primary" ghost class="nc-extdb-btn-test-connection" @click="testConnection">
{{ $t('activity.testDbConn') }}
</a-button>
<a-button type="primary" :disabled="!testSuccess" class="nc-extdb-btn-submit !shadow" @click="editBase">
{{ $t('general.submit') }}
</a-button>
</div>
</a-form-item>
</a-form>
<a-modal
v-model:visible="configEditDlg"
:title="$t('activity.editConnJson')"
width="600px"
wrap-class-name="nc-modal-edit-connection-json"
@ok="handleOk"
>
<MonacoEditor v-if="configEditDlg" v-model="customFormState" class="h-[400px] w-full" />
</a-modal>
<!-- Use Connection URL -->
<a-modal
v-model:visible="importURLDlg"
:title="$t('activity.useConnectionUrl')"
width="600px"
:ok-text="$t('general.ok')"
:cancel-text="$t('general.cancel')"
wrap-class-name="nc-modal-connection-url"
@ok="handleImportURL"
>
<a-input v-model:value="importURL" />
</a-modal>
</div>
</template>
<style lang="scss" scoped>
:deep(.ant-collapse-header) {
@apply !pr-10 !-mt-4 text-right justify-end;
}
:deep(.ant-collapse-content-box) {
@apply !px-0;
}
:deep(.ant-form-item-explain-error) {
@apply !text-xs;
}
:deep(.ant-form-item) {
@apply mb-2;
}
:deep(.ant-form-item-with-help .ant-form-item-explain) {
@apply !min-h-0;
}
.create-external {
:deep(.ant-input-affix-wrapper),
:deep(.ant-input),
:deep(.ant-select) {
@apply !appearance-none border-1 border-solid rounded;
}
:deep(.ant-input-password) {
input {
@apply !border-none my-0;
}
}
}
</style>

28
packages/nocodb/src/lib/meta/api/baseApis.ts

@ -1,6 +1,6 @@
import { Request, Response } from 'express'; import { Request, Response } from 'express';
import Project from '../../models/Project'; import Project from '../../models/Project';
import { BaseListType, ModelTypes, ProjectListType, UITypes } from 'nocodb-sdk'; import { BaseListType, ModelTypes, UITypes } from 'nocodb-sdk';
import { PagedResponseImpl } from '../helpers/PagedResponse'; import { PagedResponseImpl } from '../helpers/PagedResponse';
import { syncBaseMigration } from '../helpers/syncMigration'; import { syncBaseMigration } from '../helpers/syncMigration';
import { IGNORE_TABLES } from '../../utils/common/BaseApiBuilder'; import { IGNORE_TABLES } from '../../utils/common/BaseApiBuilder';
@ -13,7 +13,6 @@ import getTableNameAlias, { getColumnNameAlias } from '../helpers/getTableName';
import LinkToAnotherRecordColumn from '../../models/LinkToAnotherRecordColumn'; import LinkToAnotherRecordColumn from '../../models/LinkToAnotherRecordColumn';
import ncMetaAclMw from '../helpers/ncMetaAclMw'; import ncMetaAclMw from '../helpers/ncMetaAclMw';
import { Tele } from 'nc-help'; import { Tele } from 'nc-help';
import { NcError } from '../helpers/catchError';
import getColumnUiType from '../helpers/getColumnUiType'; import getColumnUiType from '../helpers/getColumnUiType';
import mapDefaultPrimaryValue from '../helpers/mapDefaultPrimaryValue'; import mapDefaultPrimaryValue from '../helpers/mapDefaultPrimaryValue';
import { extractAndGenerateManyToManyRelations } from './metaDiffApis'; import { extractAndGenerateManyToManyRelations } from './metaDiffApis';
@ -25,16 +24,33 @@ export async function baseGet(
) { ) {
const base = await Base.get(req.params.baseId); const base = await Base.get(req.params.baseId);
delete base.config; base.config = base.getConnectionConfig();
res.json(base); res.json(base);
} }
export async function baseUpdate( export async function baseUpdate(
_req: Request<any, any, any>, req: Request<any, any, any>,
_res: Response<ProjectListType> res: Response<any>
) { ) {
NcError.badRequest('Base update not yet supported'); const baseBody = req.body;
const project = await Project.getWithInfo(req.params.projectId);
const base = await Base.updateBase(req.params.baseId,
{
...baseBody,
type: baseBody.config?.client,
projectId: project.id,
id: req.params.baseId,
}
);
delete base.config;
Tele.emit('evt', {
evt_type: 'base:updated'
});
res.json(base);
} }
export async function baseList( export async function baseList(

62
packages/nocodb/src/lib/models/Base.ts

@ -11,6 +11,7 @@ import { BaseType } from 'nocodb-sdk';
import NocoCache from '../cache/NocoCache'; import NocoCache from '../cache/NocoCache';
import CryptoJS from 'crypto-js'; import CryptoJS from 'crypto-js';
import { extractProps } from '../meta/helpers/extractProps'; import { extractProps } from '../meta/helpers/extractProps';
import { NcError } from '../meta/helpers/catchError';
// todo: hide credentials // todo: hide credentials
export default class Base implements BaseType { export default class Base implements BaseType {
@ -64,6 +65,67 @@ export default class Base implements BaseType {
return this.get(id, ncMeta); return this.get(id, ncMeta);
} }
public static async updateBase(
baseId: string,
base: BaseType & { id: string; projectId: string; created_at?; updated_at? },
ncMeta = Noco.ncMeta
) {
const oldBase = await Base.get(baseId, ncMeta);
if (!oldBase) NcError.badRequest('Wrong base id!');
await ncMeta.metaDelete(null, null, MetaTable.BASES, {
id: baseId,
});
await NocoCache.deepDel(
CacheScope.BASE,
`${CacheScope.BASE}:${baseId}`,
CacheDelDirection.PARENT_TO_CHILD
);
const insertObj = extractProps(base, [
'id',
'alias',
'config',
'type',
'is_meta',
'created_at',
'updated_at',
'inflection_column',
'inflection_table',
]);
insertObj.config = CryptoJS.AES.encrypt(
JSON.stringify(base.config),
Noco.getConfig()?.auth?.jwt?.secret
).toString();
const { id } = await ncMeta.metaInsert2(
base.projectId,
null,
MetaTable.BASES,
insertObj
);
await NocoCache.appendToList(
CacheScope.BASE,
[base.projectId],
`${CacheScope.BASE}:${id}`
);
return this.get(id, ncMeta);
}
/*
await ncMeta.metaDelete(null, null, MetaTable.COL_LOOKUP, {
fk_column_id: colId,
});
await NocoCache.deepDel(
CacheScope.COL_LOOKUP,
`${CacheScope.COL_LOOKUP}:${colId}`,
CacheDelDirection.CHILD_TO_PARENT
);
*/
static async list( static async list(
args: { projectId: string }, args: { projectId: string },
ncMeta = Noco.ncMeta ncMeta = Noco.ncMeta

Loading…
Cancel
Save