feat: add decode and format selection for Hash edit

perf: move decode and format state management into the component internally

perf: add component FormatSelector and ContentEntryEditor

refactor: modified functions with an excessive number of parameters to accept an object as a parameter
This commit is contained in:
tiny-craft 2023-11-13 15:28:13 +08:00
parent a2ad85627e
commit a49d618288
16 changed files with 637 additions and 364 deletions

View File

@ -629,7 +629,8 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
case "string": case "string":
var str string var str string
str, err = client.Get(ctx, key).Result() str, err = client.Get(ctx, key).Result()
data.Value, data.DecodeType, data.ViewAs = strutil.ConvertTo(str, param.DecodeType, param.ViewAs) data.Value = strutil.EncodeRedisKey(str)
//data.Value, data.DecodeType, data.ViewAs = strutil.ConvertTo(str, param.DecodeType, param.ViewAs)
case "list": case "list":
loadListHandle := func() ([]string, bool, error) { loadListHandle := func() ([]string, bool, error) {
@ -839,184 +840,56 @@ func (b *browserService) GetKeyDetail(param types.KeyDetailParam) (resp types.JS
return return
} }
// GetKeyValue get value by key // ConvertValue convert value with decode method and format
func (b *browserService) GetKeyValue(connName string, db int, k any, viewAs, decodeType string) (resp types.JSResp) { // blank decodeType indicate auto decode
item, err := b.getRedisClient(connName, db) // blank viewAs indicate auto format
if err != nil { func (b *browserService) ConvertValue(value any, decode, format string) (resp types.JSResp) {
resp.Msg = err.Error() str := strutil.DecodeRedisKey(value)
return value, decode, format = strutil.ConvertTo(str, decode, format)
}
client, ctx := item.client, item.ctx
key := strutil.DecodeRedisKey(k)
var keyType string
var dur time.Duration
keyType, err = client.Type(ctx, key).Result()
if err != nil {
resp.Msg = err.Error()
return
}
if keyType == "none" {
resp.Msg = "key not exists"
return
}
var ttl int64
if dur, err = client.TTL(ctx, key).Result(); err != nil {
ttl = -1
} else {
if dur < 0 {
ttl = -1
} else {
ttl = int64(dur.Seconds())
}
}
var value any
var size, length int64
var cursor uint64
switch strings.ToLower(keyType) {
case "string":
var str string
str, err = client.Get(ctx, key).Result()
value, decodeType, viewAs = strutil.ConvertTo(str, decodeType, viewAs)
length, _ = client.StrLen(ctx, key).Result()
size, _ = client.MemoryUsage(ctx, key, 0).Result()
case "list":
value, err = client.LRange(ctx, key, 0, -1).Result()
length, _ = client.LLen(ctx, key).Result()
size, _ = client.MemoryUsage(ctx, key, 0).Result()
case "hash":
//value, err = client.HGetAll(ctx, key).Result()
items := map[string]string{}
scanSize := int64(Preferences().GetScanSize())
for {
var loadedVal []string
loadedVal, cursor, err = client.HScan(ctx, key, cursor, "*", scanSize).Result()
if err != nil {
resp.Msg = err.Error()
return
}
for i := 0; i < len(loadedVal); i += 2 {
items[loadedVal[i]] = loadedVal[i+1]
}
if cursor == 0 {
break
}
}
value = items
length, _ = client.HLen(ctx, key).Result()
size, _ = client.MemoryUsage(ctx, key, 0).Result()
case "set":
//value, err = client.SMembers(ctx, key).Result()
items := []string{}
scanSize := int64(Preferences().GetScanSize())
for {
var loadedKey []string
loadedKey, cursor, err = client.SScan(ctx, key, cursor, "*", scanSize).Result()
if err != nil {
resp.Msg = err.Error()
return
}
items = append(items, loadedKey...)
if cursor == 0 {
break
}
}
value = items
length, _ = client.SCard(ctx, key).Result()
size, _ = client.MemoryUsage(ctx, key, 0).Result()
case "zset":
//value, err = client.ZRangeWithScores(ctx, key, 0, -1).Result()
var items []types.ZSetItem
scanSize := int64(Preferences().GetScanSize())
for {
var loadedVal []string
loadedVal, cursor, err = client.ZScan(ctx, key, cursor, "*", scanSize).Result()
if err != nil {
resp.Msg = err.Error()
return
}
var score float64
for i := 0; i < len(loadedVal); i += 2 {
if score, err = strconv.ParseFloat(loadedVal[i+1], 64); err == nil {
items = append(items, types.ZSetItem{
Value: loadedVal[i],
Score: score,
})
}
}
if cursor == 0 {
break
}
}
value = items
length, _ = client.ZCard(ctx, key).Result()
size, _ = client.MemoryUsage(ctx, key, 0).Result()
case "stream":
var msgs []redis.XMessage
items := []types.StreamItem{}
msgs, err = client.XRevRange(ctx, key, "+", "-").Result()
if err != nil {
resp.Msg = err.Error()
return
}
for _, msg := range msgs {
items = append(items, types.StreamItem{
ID: msg.ID,
Value: msg.Values,
})
}
value = items
length, _ = client.XLen(ctx, key).Result()
size, _ = client.MemoryUsage(ctx, key, 0).Result()
}
if err != nil {
resp.Msg = err.Error()
return
}
resp.Success = true resp.Success = true
resp.Data = map[string]any{ resp.Data = map[string]any{
"type": keyType,
"ttl": ttl,
"value": value, "value": value,
"size": size, "decode": decode,
"length": length, "format": format,
"viewAs": viewAs,
"decode": decodeType,
} }
return return
} }
// SetKeyValue set value by key // SetKeyValue set value by key
// @param ttl <= 0 means keep current ttl // @param ttl <= 0 means keep current ttl
func (b *browserService) SetKeyValue(connName string, db int, k any, keyType string, value any, ttl int64, viewAs, decode string) (resp types.JSResp) { func (b *browserService) SetKeyValue(param types.SetKeyParam) (resp types.JSResp) {
item, err := b.getRedisClient(connName, db) item, err := b.getRedisClient(param.Server, param.DB)
if err != nil { if err != nil {
resp.Msg = err.Error() resp.Msg = err.Error()
return return
} }
client, ctx := item.client, item.ctx client, ctx := item.client, item.ctx
key := strutil.DecodeRedisKey(k) key := strutil.DecodeRedisKey(param.Key)
var expiration time.Duration var expiration time.Duration
if ttl < 0 { if param.TTL < 0 {
if expiration, err = client.PTTL(ctx, key).Result(); err != nil { if expiration, err = client.PTTL(ctx, key).Result(); err != nil {
expiration = redis.KeepTTL expiration = redis.KeepTTL
} }
} else { } else {
expiration = time.Duration(ttl) * time.Second expiration = time.Duration(param.TTL) * time.Second
} }
switch strings.ToLower(keyType) { // use default decode type and format
if len(param.Decode) <= 0 {
param.Decode = types.DECODE_NONE
}
if len(param.Format) <= 0 {
param.Format = types.VIEWAS_PLAIN_TEXT
}
switch strings.ToLower(param.KeyType) {
case "string": case "string":
if str, ok := value.(string); !ok { if str, ok := param.Value.(string); !ok {
resp.Msg = "invalid string value" resp.Msg = "invalid string value"
return return
} else { } else {
var saveStr string var saveStr string
if saveStr, err = strutil.SaveAs(str, viewAs, decode); err != nil { if saveStr, err = strutil.SaveAs(str, param.Format, param.Decode); err != nil {
resp.Msg = fmt.Sprintf(`save to "%s" type fail: %s`, viewAs, err.Error()) resp.Msg = fmt.Sprintf(`save to "%s" type fail: %s`, param.Format, err.Error())
return return
} }
_, err = client.Set(ctx, key, saveStr, 0).Result() _, err = client.Set(ctx, key, saveStr, 0).Result()
@ -1026,7 +899,7 @@ func (b *browserService) SetKeyValue(connName string, db int, k any, keyType str
} }
} }
case "list": case "list":
if strs, ok := value.([]any); !ok { if strs, ok := param.Value.([]any); !ok {
resp.Msg = "invalid list value" resp.Msg = "invalid list value"
return return
} else { } else {
@ -1036,7 +909,7 @@ func (b *browserService) SetKeyValue(connName string, db int, k any, keyType str
} }
} }
case "hash": case "hash":
if strs, ok := value.([]any); !ok { if strs, ok := param.Value.([]any); !ok {
resp.Msg = "invalid hash value" resp.Msg = "invalid hash value"
return return
} else { } else {
@ -1054,7 +927,7 @@ func (b *browserService) SetKeyValue(connName string, db int, k any, keyType str
} }
} }
case "set": case "set":
if strs, ok := value.([]any); !ok || len(strs) <= 0 { if strs, ok := param.Value.([]any); !ok || len(strs) <= 0 {
resp.Msg = "invalid set value" resp.Msg = "invalid set value"
return return
} else { } else {
@ -1066,7 +939,7 @@ func (b *browserService) SetKeyValue(connName string, db int, k any, keyType str
} }
} }
case "zset": case "zset":
if strs, ok := value.([]any); !ok || len(strs) <= 0 { if strs, ok := param.Value.([]any); !ok || len(strs) <= 0 {
resp.Msg = "invalid zset value" resp.Msg = "invalid zset value"
return return
} else { } else {
@ -1086,7 +959,7 @@ func (b *browserService) SetKeyValue(connName string, db int, k any, keyType str
} }
} }
case "stream": case "stream":
if strs, ok := value.([]any); !ok { if strs, ok := param.Value.([]any); !ok {
resp.Msg = "invalid stream value" resp.Msg = "invalid stream value"
return return
} else { } else {
@ -1109,46 +982,52 @@ func (b *browserService) SetKeyValue(connName string, db int, k any, keyType str
} }
resp.Success = true resp.Success = true
resp.Data = map[string]any{ resp.Data = map[string]any{
"value": value, "value": param.Value,
} }
return return
} }
// SetHashValue set hash field // SetHashValue set hash field
func (b *browserService) SetHashValue(connName string, db int, k any, field, newField, value string) (resp types.JSResp) { func (b *browserService) SetHashValue(param types.SetHashParam) (resp types.JSResp) {
item, err := b.getRedisClient(connName, db) item, err := b.getRedisClient(param.Server, param.DB)
if err != nil { if err != nil {
resp.Msg = err.Error() resp.Msg = err.Error()
return return
} }
client, ctx := item.client, item.ctx client, ctx := item.client, item.ctx
key := strutil.DecodeRedisKey(k) key := strutil.DecodeRedisKey(param.Key)
str := strutil.DecodeRedisKey(param.Value)
var saveStr string
if saveStr, err = strutil.SaveAs(str, param.Format, param.Decode); err != nil {
resp.Msg = fmt.Sprintf(`save to "%s" type fail: %s`, param.Format, err.Error())
return
}
var removedField []string var removedField []string
updatedField := map[string]string{} updatedField := map[string]any{}
replacedField := map[string]string{} replacedField := map[string]any{}
if len(field) <= 0 { if len(param.Field) <= 0 {
// old filed is empty, add new field // old filed is empty, add new field
_, err = client.HSet(ctx, key, newField, value).Result() _, err = client.HSet(ctx, key, param.NewField, saveStr).Result()
updatedField[newField] = value updatedField[param.NewField] = saveStr
} else if len(newField) <= 0 { } else if len(param.NewField) <= 0 {
// new field is empty, delete old field // new field is empty, delete old field
_, err = client.HDel(ctx, key, field, value).Result() _, err = client.HDel(ctx, key, param.Field).Result()
removedField = append(removedField, field) removedField = append(removedField, param.Field)
} else if field == newField { } else if param.Field == param.NewField {
// replace field // update field value
_, err = client.HSet(ctx, key, newField, value).Result() _, err = client.HSet(ctx, key, param.Field, saveStr).Result()
updatedField[newField] = value updatedField[param.NewField] = saveStr
} else { } else {
// remove old field and add new field // remove old field and add new field
if _, err = client.HDel(ctx, key, field).Result(); err != nil { if _, err = client.HDel(ctx, key, param.Field).Result(); err != nil {
resp.Msg = err.Error() resp.Msg = err.Error()
return return
} }
_, err = client.HSet(ctx, key, newField, value).Result() _, err = client.HSet(ctx, key, param.NewField, saveStr).Result()
removedField = append(removedField, field) removedField = append(removedField, param.Field)
updatedField[newField] = value updatedField[param.NewField] = saveStr
replacedField[field] = newField replacedField[param.Field] = param.NewField
} }
if err != nil { if err != nil {
resp.Msg = err.Error() resp.Msg = err.Error()

View File

@ -37,3 +37,25 @@ type KeyDetail struct {
DecodeType string `json:"decodeType,omitempty"` DecodeType string `json:"decodeType,omitempty"`
End bool `json:"end"` End bool `json:"end"`
} }
type SetKeyParam struct {
Server string `json:"server"`
DB int `json:"db"`
Key any `json:"key"`
KeyType string `json:"keyType"`
Value any `json:"value"`
TTL int64 `json:"ttl"`
Format string `json:"format,omitempty"`
Decode string `json:"decode,omitempty"`
}
type SetHashParam struct {
Server string `json:"server"`
DB int `json:"db"`
Key any `json:"key"`
Field string `json:"field,omitempty"`
NewField string `json:"newField,omitempty"`
Value any `json:"value"`
Format string `json:"format,omitempty"`
Decode string `json:"decode,omitempty"`
}

View File

@ -1,6 +1,6 @@
<script setup> <script setup>
import { computed, h, ref } from 'vue' import { computed, h, ref } from 'vue'
import { map } from 'lodash' import { get, map } from 'lodash'
import { NIcon, NText } from 'naive-ui' import { NIcon, NText } from 'naive-ui'
const props = defineProps({ const props = defineProps({
@ -16,6 +16,8 @@ const props = defineProps({
type: String, type: String,
}, },
icon: [String, Object], icon: [String, Object],
default: String,
disabled: Boolean,
}) })
const emit = defineEmits(['update:value']) const emit = defineEmits(['update:value'])
@ -56,7 +58,7 @@ const onDropdownSelect = (key) => {
} }
const buttonText = computed(() => { const buttonText = computed(() => {
return props.value || get(dropdownOption.value, [1, 'label'], 'None') return props.value || get(dropdownOption.value, [1, 'label'], props.default)
}) })
const showDropdown = ref(false) const showDropdown = ref(false)
@ -67,6 +69,7 @@ const onDropdownShow = (show) => {
<template> <template>
<n-dropdown <n-dropdown
:disabled="props.disabled"
:options="dropdownOption" :options="dropdownOption"
:render-label="renderLabel" :render-label="renderLabel"
:show-arrow="true" :show-arrow="true"
@ -78,7 +81,7 @@ const onDropdownShow = (show) => {
<n-tooltip :disabled="showDropdown" :show-arrow="false"> <n-tooltip :disabled="showDropdown" :show-arrow="false">
{{ props.tooltip }} {{ props.tooltip }}
<template #trigger> <template #trigger>
<n-button :focusable="false" quaternary> <n-button :disabled="disabled" :focusable="false" quaternary>
<template #icon> <template #icon>
<n-icon> <n-icon>
<component :is="icon" /> <component :is="icon" />

View File

@ -7,6 +7,7 @@ const emit = defineEmits(['click'])
const props = defineProps({ const props = defineProps({
tooltip: String, tooltip: String,
tTooltip: String, tTooltip: String,
type: String,
icon: [String, Object], icon: [String, Object],
size: { size: {
type: [Number, String], type: [Number, String],
@ -39,6 +40,7 @@ const hasTooltip = computed(() => {
:focusable="false" :focusable="false"
:loading="loading" :loading="loading"
:text="!border" :text="!border"
:type="type"
@click.prevent="emit('click')"> @click.prevent="emit('click')">
<template #icon> <template #icon>
<n-icon :color="props.color || 'currentColor'" :size="props.size"> <n-icon :color="props.color || 'currentColor'" :size="props.size">
@ -56,6 +58,7 @@ const hasTooltip = computed(() => {
:focusable="false" :focusable="false"
:loading="loading" :loading="loading"
:text="!border" :text="!border"
:type="type"
@click.prevent="emit('click')"> @click.prevent="emit('click')">
<template #icon> <template #icon>
<n-icon :color="props.color || 'currentColor'" :size="props.size"> <n-icon :color="props.color || 'currentColor'" :size="props.size">

View File

@ -2,7 +2,7 @@
import { computed, h, nextTick, reactive, ref } from 'vue' import { computed, h, nextTick, reactive, ref } from 'vue'
import IconButton from '@/components/common/IconButton.vue' import IconButton from '@/components/common/IconButton.vue'
import Refresh from '@/components/icons/Refresh.vue' import Refresh from '@/components/icons/Refresh.vue'
import { map, size, split, uniqBy } from 'lodash' import { map, size, uniqBy } from 'lodash'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import Delete from '@/components/icons/Delete.vue' import Delete from '@/components/icons/Delete.vue'
import dayjs from 'dayjs' import dayjs from 'dayjs'

View File

@ -0,0 +1,180 @@
<script setup>
import { computed, defineEmits, defineProps, reactive, ref, watch } from 'vue'
import { useThemeVars } from 'naive-ui'
import Save from '@/components/icons/Save.vue'
import { decodeTypes, formatTypes } from '@/consts/value_view_type.js'
import { decodeRedisKey } from '@/utils/key_convert.js'
import useBrowserStore from 'stores/browser.js'
import FormatSelector from '@/components/content_value/FormatSelector.vue'
const props = defineProps({
field: {
type: String,
},
value: {
type: String,
},
keyLabel: {
type: String,
},
valueLabel: {
type: String,
},
decode: {
type: String,
},
format: {
type: String,
},
})
const themeVars = useThemeVars()
const browserStore = useBrowserStore()
const emit = defineEmits(['update:field', 'update:value', 'update:decode', 'update:format', 'viewAs', 'save', 'cancel'])
const model = reactive({
field: '',
value: '',
})
watch(
() => props.value,
(val) => {
if (val != null) {
onFormatChanged()
} else {
viewAs.value = ''
}
},
)
const loading = ref(false)
const viewAs = reactive({
field: '',
value: '',
format: formatTypes.PLAIN_TEXT,
decode: decodeTypes.NONE,
})
const displayValue = computed(() => {
if (loading.value) {
return ''
}
return viewAs.value || decodeRedisKey(props.value)
})
/**
*
* @param {string} decode
* @param {string} format
* @return {Promise<void>}
*/
const onFormatChanged = async (decode = '', format = '') => {
try {
loading.value = true
const {
value,
decode: retDecode,
format: retFormat,
} = await browserStore.convertValue({
value: props.value,
decode,
format,
})
viewAs.field = props.field
viewAs.value = value
viewAs.decode = decode || retDecode
viewAs.format = format || retFormat
} finally {
loading.value = false
}
}
const onUpdateValue = (value) => {
// TODO: reconvert back to origin format
// emit('update:value', value)
viewAs.value = value
}
const onSave = () => {
// TODO: convert value by decode and format
// viewAs.decode, viewAs.format
emit('save', viewAs.field, viewAs.value, viewAs.decode, viewAs.format)
}
</script>
<template>
<div class="entry-editor flex-box-v">
<n-card
:title="$t('interface.edit_row')"
autofocus
closable
size="small"
style="height: 100%"
@close="emit('cancel')">
<div class="editor-content flex-box-v" style="height: 100%">
<!-- field -->
<div class="editor-content-item flex-box-v">
<div class="editor-content-item-label">{{ props.keyLabel }}</div>
<n-input v-model:value="viewAs.field" class="editor-content-item-input" type="text" />
</div>
<!-- value -->
<div class="editor-content-item flex-box-v flex-item-expand">
<div class="editor-content-item-label">{{ props.valueLabel }}</div>
<n-input
:value="displayValue"
autofocus
class="flex-item-expand"
type="textarea"
@update:value="onUpdateValue" />
<format-selector
:decode="viewAs.decode"
:format="viewAs.format"
@format-changed="(d, f) => onFormatChanged(d, f)" />
</div>
</div>
<template #action>
<n-space :wrap="false" :wrap-item="false" justify="end">
<n-button ghost type="primary" @click="onSave">
<template #icon>
<n-icon :component="Save"></n-icon>
</template>
{{ $t('common.update') }}
</n-button>
</n-space>
</template>
</n-card>
</div>
</template>
<style lang="scss" scoped>
.entry-editor {
padding-left: 2px;
.editor-content {
&-item {
&:not(:last-child) {
margin-bottom: 18px;
}
&-label {
line-height: 1.25;
color: v-bind('themeVars.textColor3');
font-size: 13px;
padding: 5px 0;
}
&-input {
}
}
}
}
:deep(.n-card__action) {
padding: 5px 10px;
background-color: unset;
}
:deep(.n-card--bordered) {
border-radius: 0;
}
</style>

View File

@ -3,7 +3,7 @@ import { computed, h, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import ContentToolbar from './ContentToolbar.vue' import ContentToolbar from './ContentToolbar.vue'
import AddLink from '@/components/icons/AddLink.vue' import AddLink from '@/components/icons/AddLink.vue'
import { NButton, NCode, NIcon, NInput, useThemeVars } from 'naive-ui' import { NButton, NIcon, NInput, useThemeVars } from 'naive-ui'
import { types, types as redisTypes } from '@/consts/support_redis_type.js' import { types, types as redisTypes } from '@/consts/support_redis_type.js'
import EditableTableColumn from '@/components/common/EditableTableColumn.vue' import EditableTableColumn from '@/components/common/EditableTableColumn.vue'
import useDialogStore from 'stores/dialog.js' import useDialogStore from 'stores/dialog.js'
@ -14,6 +14,8 @@ import useBrowserStore from 'stores/browser.js'
import LoadList from '@/components/icons/LoadList.vue' import LoadList from '@/components/icons/LoadList.vue'
import LoadAll from '@/components/icons/LoadAll.vue' import LoadAll from '@/components/icons/LoadAll.vue'
import IconButton from '@/components/common/IconButton.vue' import IconButton from '@/components/common/IconButton.vue'
import ContentEntryEditor from '@/components/content_value/ContentEntryEditor.vue'
import Edit from '@/components/icons/Edit.vue'
const i18n = useI18n() const i18n = useI18n()
const themeVars = useThemeVars() const themeVars = useThemeVars()
@ -33,7 +35,7 @@ const props = defineProps({
value: Object, value: Object,
size: Number, size: Number,
length: Number, length: Number,
viewAs: { format: {
type: String, type: String,
default: formatTypes.PLAIN_TEXT, default: formatTypes.PLAIN_TEXT,
}, },
@ -74,31 +76,27 @@ const currentEditRow = ref({
no: 0, no: 0,
key: '', key: '',
value: null, value: null,
format: formatTypes.PLAIN_TEXT,
decode: decodeTypes.NONE,
}) })
const inEdit = computed(() => {
return currentEditRow.value.no > 0
})
const tableRef = ref(null)
const fieldColumn = reactive({ const fieldColumn = reactive({
key: 'key', key: 'key',
title: i18n.t('common.field'), title: i18n.t('common.field'),
align: 'center', align: 'center',
titleAlign: 'center', titleAlign: 'center',
resizable: true, resizable: true,
ellipsis: {
tooltip: true,
},
filterOptionValue: null, filterOptionValue: null,
filter(value, row) { filter(value, row) {
return !!~row.key.indexOf(value.toString()) return !!~row.key.indexOf(value.toString())
}, },
// sorter: (row1, row2) => row1.key - row2.key,
render: (row) => {
const isEdit = currentEditRow.value.no === row.no
if (isEdit) {
return h(NInput, {
value: currentEditRow.value.key,
'onUpdate:value': (val) => {
currentEditRow.value.key = val
},
})
} else {
return row.key
}
},
}) })
const valueColumn = reactive({ const valueColumn = reactive({
key: 'value', key: 'value',
@ -106,34 +104,58 @@ const valueColumn = reactive({
align: 'center', align: 'center',
titleAlign: 'center', titleAlign: 'center',
resizable: true, resizable: true,
ellipsis: {
tooltip: true,
},
filterOptionValue: null, filterOptionValue: null,
filter(value, row) { filter(value, row) {
return !!~row.value.indexOf(value.toString()) return !!~row.value.indexOf(value.toString())
}, },
// sorter: (row1, row2) => row1.value - row2.value,
// ellipsis: {
// tooltip: true
// },
render: (row) => {
const isEdit = currentEditRow.value.no === row.no
if (isEdit) {
return h(NInput, {
value: currentEditRow.value.value,
type: 'textarea',
autosize: { minRow: 2, maxRows: 5 },
style: 'text-align: left;',
'onUpdate:value': (val) => {
currentEditRow.value.value = val
},
})
} else {
return h(NCode, { language: 'plaintext', wordWrap: true }, { default: () => row.value })
}
},
}) })
const cancelEdit = () => { const startEdit = async ({ no, key, value }) => {
currentEditRow.value.value = value
currentEditRow.value.no = no
currentEditRow.value.key = key
}
const saveEdit = async (field, value, decode, format) => {
try {
const row = tableData.value[currentEditRow.value.no - 1]
if (row == null) {
throw new Error('row not exists')
}
const { updated, success, msg } = await browserStore.setHash({
server: props.name,
db: props.db,
key: keyName.value,
field: row.key,
newField: field,
value,
decode,
format,
})
if (success) {
row.key = field
row.value = updated[row.key] || ''
$message.success(i18n.t('dialogue.save_value_succ'))
} else {
$message.error(msg)
}
} catch (e) {
$message.error(e.message)
} finally {
resetEdit()
}
}
const resetEdit = () => {
currentEditRow.value.no = 0 currentEditRow.value.no = 0
currentEditRow.value.key = ''
currentEditRow.value.value = null
currentEditRow.value.format = formatTypes.PLAIN_TEXT
currentEditRow.value.decode = decodeTypes.NONE
} }
const actionColumn = { const actionColumn = {
@ -145,13 +167,9 @@ const actionColumn = {
fixed: 'right', fixed: 'right',
render: (row) => { render: (row) => {
return h(EditableTableColumn, { return h(EditableTableColumn, {
editing: currentEditRow.value.no === row.no, editing: false,
bindKey: row.key, bindKey: row.key,
onEdit: () => { onEdit: () => startEdit(row),
currentEditRow.value.no = row.no
currentEditRow.value.key = row.key
currentEditRow.value.value = row.value
},
onDelete: async () => { onDelete: async () => {
try { try {
const { success, msg } = await browserStore.removeHashField( const { success, msg } = await browserStore.removeHashField(
@ -169,43 +187,45 @@ const actionColumn = {
$message.error(e.message) $message.error(e.message)
} }
}, },
onSave: async () => {
try {
const { success, msg } = await browserStore.setHash(
props.name,
props.db,
keyName.value,
row.key,
currentEditRow.value.key,
currentEditRow.value.value,
)
if (success) {
$message.success(i18n.t('dialogue.save_value_succ'))
} else {
$message.error(msg)
}
} catch (e) {
$message.error(e.message)
} finally {
currentEditRow.value.no = 0
}
},
onCancel: cancelEdit,
}) })
}, },
} }
const columns = reactive([
{ const columns = computed(() => {
key: 'no', if (!inEdit.value) {
title: '#', return [
width: 80, {
align: 'center', key: 'no',
titleAlign: 'center', title: '#',
}, width: 80,
fieldColumn, align: 'center',
valueColumn, titleAlign: 'center',
actionColumn, },
]) fieldColumn,
valueColumn,
actionColumn,
]
} else {
return [
{
key: 'no',
title: '#',
width: 80,
align: 'center',
titleAlign: 'center',
render(row) {
if (row.no === currentEditRow.value.no) {
// editing row, show edit state
return h(NIcon, { size: 16, color: 'red' }, () => h(Edit, { strokeWidth: 5 }))
} else {
return row.no
}
},
},
fieldColumn,
]
}
})
const tableData = computed(() => { const tableData = computed(() => {
const data = [] const data = []
@ -220,6 +240,17 @@ const tableData = computed(() => {
return data return data
}) })
const rowProps = (row) => {
return {
onClick: () => {
// in edit mode, switch edit row by click
if (inEdit.value) {
startEdit(row)
}
},
}
}
const entries = computed(() => { const entries = computed(() => {
const len = size(tableData.value) const len = size(tableData.value)
return `${len} / ${Math.max(len, props.length)}` return `${len} / ${Math.max(len, props.length)}`
@ -232,12 +263,12 @@ const onAddRow = () => {
const filterValue = ref('') const filterValue = ref('')
const onFilterInput = (val) => { const onFilterInput = (val) => {
switch (filterType.value) { switch (filterType.value) {
case filterOption[0].value: case filterOption.value[0].value:
// filter field // filter field
valueColumn.filterOptionValue = null valueColumn.filterOptionValue = null
fieldColumn.filterOptionValue = val fieldColumn.filterOptionValue = val
break break
case filterOption[1].value: case filterOption.value[1].value:
// filter value // filter value
fieldColumn.filterOptionValue = null fieldColumn.filterOptionValue = null
valueColumn.filterOptionValue = val valueColumn.filterOptionValue = val
@ -256,10 +287,10 @@ const clearFilter = () => {
const onUpdateFilter = (filters, sourceColumn) => { const onUpdateFilter = (filters, sourceColumn) => {
switch (filterType.value) { switch (filterType.value) {
case filterOption[0].value: case filterOption.value[0].value:
fieldColumn.filterOptionValue = filters[sourceColumn.key] fieldColumn.filterOptionValue = filters[sourceColumn.key]
break break
case filterOption[1].value: case filterOption.value[1].value:
valueColumn.filterOptionValue = filters[sourceColumn.key] valueColumn.filterOptionValue = filters[sourceColumn.key]
break break
} }
@ -268,7 +299,7 @@ const onUpdateFilter = (filters, sourceColumn) => {
defineExpose({ defineExpose({
reset: () => { reset: () => {
clearFilter() clearFilter()
cancelEdit() resetEdit()
}, },
}) })
</script> </script>
@ -328,14 +359,17 @@ defineExpose({
{{ $t('interface.add_row') }} {{ $t('interface.add_row') }}
</n-button> </n-button>
</div> </div>
<div class="value-wrapper value-item-part flex-box-v flex-item-expand"> <div id="content-table" class="value-wrapper value-item-part flex-box-h flex-item-expand">
<!-- table -->
<n-data-table <n-data-table
:key="(row) => row.no" :key="(row) => row.no"
ref="tableRef"
:bordered="false" :bordered="false"
:bottom-bordered="false" :bottom-bordered="false"
:columns="columns" :columns="columns"
:data="tableData" :data="tableData"
:loading="props.loading" :loading="props.loading"
:row-props="rowProps"
:single-column="true" :single-column="true"
:single-line="false" :single-line="false"
class="flex-item-expand" class="flex-item-expand"
@ -344,6 +378,20 @@ defineExpose({
striped striped
virtual-scroll virtual-scroll
@update:filters="onUpdateFilter" /> @update:filters="onUpdateFilter" />
<!-- edit pane -->
<content-entry-editor
v-show="inEdit"
:decode="currentEditRow.decode"
:field="currentEditRow.key"
:format="currentEditRow.format"
:key-label="$t('common.field')"
:value="currentEditRow.value"
:value-label="$t('common.value')"
class="flex-item-expand"
style="width: 100%"
@cancel="resetEdit"
@save="saveEdit" />
</div> </div>
<div class="value-footer flex-box-h"> <div class="value-footer flex-box-h">
<n-text v-if="!isNaN(props.length)">{{ $t('interface.entries') }}: {{ entries }}</n-text> <n-text v-if="!isNaN(props.length)">{{ $t('interface.entries') }}: {{ entries }}</n-text>

View File

@ -1,5 +1,5 @@
<script setup> <script setup>
import { computed, ref } from 'vue' import { computed, reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import ContentToolbar from './ContentToolbar.vue' import ContentToolbar from './ContentToolbar.vue'
import Copy from '@/components/icons/Copy.vue' import Copy from '@/components/icons/Copy.vue'
@ -10,12 +10,11 @@ import Close from '@/components/icons/Close.vue'
import { types as redisTypes } from '@/consts/support_redis_type.js' import { types as redisTypes } from '@/consts/support_redis_type.js'
import { ClipboardSetText } from 'wailsjs/runtime/runtime.js' import { ClipboardSetText } from 'wailsjs/runtime/runtime.js'
import { isEmpty, toLower } from 'lodash' import { isEmpty, toLower } from 'lodash'
import DropdownSelector from '@/components/content_value/DropdownSelector.vue'
import Code from '@/components/icons/Code.vue'
import Conversion from '@/components/icons/Conversion.vue'
import EditFile from '@/components/icons/EditFile.vue' import EditFile from '@/components/icons/EditFile.vue'
import bytes from 'bytes' import bytes from 'bytes'
import useBrowserStore from 'stores/browser.js' import useBrowserStore from 'stores/browser.js'
import { decodeRedisKey } from '@/utils/key_convert.js'
import FormatSelector from '@/components/content_value/FormatSelector.vue'
const i18n = useI18n() const i18n = useI18n()
const themeVars = useThemeVars() const themeVars = useThemeVars()
@ -32,17 +31,9 @@ const props = defineProps({
type: Number, type: Number,
default: -1, default: -1,
}, },
value: String, value: [String, Array],
size: Number, size: Number,
length: Number, length: Number,
viewAs: {
type: String,
default: formatTypes.PLAIN_TEXT,
},
decode: {
type: String,
default: decodeTypes.NONE,
},
loading: Boolean, loading: Boolean,
}) })
@ -58,7 +49,7 @@ const keyName = computed(() => {
const keyType = redisTypes.STRING const keyType = redisTypes.STRING
const viewLanguage = computed(() => { const viewLanguage = computed(() => {
switch (props.viewAs) { switch (viewAs.format) {
case formatTypes.JSON: case formatTypes.JSON:
return 'json' return 'json'
default: default:
@ -66,31 +57,48 @@ const viewLanguage = computed(() => {
} }
}) })
const onViewTypeUpdate = (viewType) => { const viewAs = reactive({
browserStore.loadKeyDetail({ value: '',
server: props.name, format: formatTypes.PLAIN_TEXT,
db: props.db, decode: decodeTypes.NONE,
key: keyName.value, })
viewType,
decodeType: props.decode,
})
}
const onDecodeTypeUpdate = (decodeType) => { const displayValue = computed(() => {
browserStore.loadKeyDetail({ if (props.loading) {
server: props.name, return ''
db: props.db, }
key: keyName.value, return viewAs.value || decodeRedisKey(props.value)
viewType: props.viewAs, })
decodeType,
watch(
() => props.value,
(val, oldVal) => {
if (val !== undefined && oldVal !== undefined) {
onFormatChanged(viewAs.decode, viewAs.format)
}
},
)
const onFormatChanged = async (decode = '', format = '') => {
const {
value,
decode: retDecode,
format: retFormat,
} = await browserStore.convertValue({
value: props.value,
decode,
format,
}) })
viewAs.value = value
viewAs.decode = decode || retDecode
viewAs.format = format || retFormat
} }
/** /**
* Copy value * Copy value
*/ */
const onCopyValue = () => { const onCopyValue = () => {
ClipboardSetText(props.value) ClipboardSetText(displayValue.value)
.then((succ) => { .then((succ) => {
if (succ) { if (succ) {
$message.success(i18n.t('dialogue.copy_succ')) $message.success(i18n.t('dialogue.copy_succ'))
@ -104,7 +112,7 @@ const onCopyValue = () => {
const editValue = ref('') const editValue = ref('')
const inEdit = ref(false) const inEdit = ref(false)
const onEditValue = () => { const onEditValue = () => {
editValue.value = props.value editValue.value = displayValue.value
inEdit.value = true inEdit.value = true
} }
@ -120,16 +128,16 @@ const saving = ref(false)
const onSaveValue = async () => { const onSaveValue = async () => {
saving.value = true saving.value = true
try { try {
const { success, msg } = await browserStore.setKey( const { success, msg } = await browserStore.setKey({
props.name, server: props.name,
props.db, db: props.db,
keyName.value, key: keyName.value,
toLower(keyType), keyType: toLower(keyType),
editValue.value, value: editValue.value,
-1, ttl: -1,
props.viewAs, format: viewAs.format,
props.decode, decode: viewAs.decode,
) })
if (success) { if (success) {
await browserStore.loadKeyDetail({ server: props.name, db: props.db, key: keyName.value }) await browserStore.loadKeyDetail({ server: props.name, db: props.db, key: keyName.value })
$message.success(i18n.t('dialogue.save_value_succ')) $message.success(i18n.t('dialogue.save_value_succ'))
@ -146,8 +154,10 @@ const onSaveValue = async () => {
defineExpose({ defineExpose({
reset: () => { reset: () => {
viewAs.value = ''
inEdit.value = false inEdit.value = false
}, },
beforeShow: () => onFormatChanged(),
}) })
</script> </script>
@ -198,7 +208,7 @@ defineExpose({
</div> </div>
<div class="value-wrapper value-item-part flex-item-expand flex-box-v"> <div class="value-wrapper value-item-part flex-item-expand flex-box-v">
<n-scrollbar v-if="!inEdit" class="flex-item-expand"> <n-scrollbar v-if="!inEdit" class="flex-item-expand">
<n-code :code="props.value" :language="viewLanguage" style="cursor: text" word-wrap /> <n-code :code="displayValue" :language="viewLanguage" style="cursor: text" word-wrap />
</n-scrollbar> </n-scrollbar>
<n-input <n-input
v-else v-else
@ -213,19 +223,11 @@ defineExpose({
<n-divider v-if="!isNaN(props.length)" vertical /> <n-divider v-if="!isNaN(props.length)" vertical />
<n-text v-if="!isNaN(props.size)">{{ $t('interface.memory_usage') }}: {{ bytes(props.size) }}</n-text> <n-text v-if="!isNaN(props.size)">{{ $t('interface.memory_usage') }}: {{ bytes(props.size) }}</n-text>
<div class="flex-item-expand"></div> <div class="flex-item-expand"></div>
<dropdown-selector <format-selector
:icon="Code" :decode="viewAs.decode"
:options="formatTypes" :disabled="inEdit"
:tooltip="$t('interface.view_as')" :format="viewAs.format"
:value="props.viewAs" @format-changed="onFormatChanged" />
@update:value="onViewTypeUpdate" />
<n-divider vertical />
<dropdown-selector
:icon="Conversion"
:options="decodeTypes"
:tooltip="$t('interface.decode_with')"
:value="props.decode"
@update:value="onDecodeTypeUpdate" />
</div> </div>
</div> </div>
</template> </template>

View File

@ -10,7 +10,6 @@ import { useThemeVars } from 'naive-ui'
import useBrowserStore from 'stores/browser.js' import useBrowserStore from 'stores/browser.js'
import { computed, onMounted, ref, watch } from 'vue' import { computed, onMounted, ref, watch } from 'vue'
import { isEmpty } from 'lodash' import { isEmpty } from 'lodash'
import { decodeTypes, formatTypes } from '@/consts/value_view_type.js'
import useDialogStore from 'stores/dialog.js' import useDialogStore from 'stores/dialog.js'
const themeVars = useThemeVars() const themeVars = useThemeVars()
@ -45,6 +44,7 @@ const props = defineProps({
const data = computed(() => { const data = computed(() => {
return props.content return props.content
}) })
const initializing = ref(false)
const binaryKey = computed(() => { const binaryKey = computed(() => {
return !!data.value.keyCode return !!data.value.keyCode
@ -116,22 +116,29 @@ const onLoadAll = () => {
loadData(false, true) loadData(false, true)
} }
onMounted(() => { const initContent = async () => {
// onReload() // onReload()
loadData(false, false) try {
}) initializing.value = true
const contentRef = ref(null)
watch(
() => data.value?.keyPath,
() => {
// onReload()
if (contentRef.value?.reset != null) { if (contentRef.value?.reset != null) {
contentRef.value?.reset() contentRef.value?.reset()
} }
loadData(false, false) await loadData(false, false)
}, if (contentRef.value?.beforeShow != null) {
) await contentRef.value?.beforeShow()
}
} finally {
initializing.value = false
}
}
onMounted(() => {
// onReload()
initContent()
})
const contentRef = ref(null)
watch(() => data.value?.keyPath, initContent)
</script> </script>
<template> <template>
@ -145,17 +152,15 @@ watch(
:is="valueComponents[data.type]" :is="valueComponents[data.type]"
ref="contentRef" ref="contentRef"
:db="data.db" :db="data.db"
:decode="data.decode || decodeTypes.NONE"
:end="data.end" :end="data.end"
:key-code="data.keyCode" :key-code="data.keyCode"
:key-path="data.keyPath" :key-path="data.keyPath"
:length="data.length" :length="data.length"
:loading="data.loading === true" :loading="data.loading === true || initializing"
:name="data.name" :name="data.name"
:size="data.size" :size="data.size"
:ttl="data.ttl" :ttl="data.ttl"
:value="data.value" :value="data.value"
:view-as="data.viewAs || formatTypes.PLAIN_TEXT"
@delete="onDelete" @delete="onDelete"
@loadall="onLoadAll" @loadall="onLoadAll"
@loadmore="onLoadMore" @loadmore="onLoadMore"

View File

@ -0,0 +1,60 @@
<script setup>
import { decodeTypes, formatTypes } from '@/consts/value_view_type.js'
import Code from '@/components/icons/Code.vue'
import Conversion from '@/components/icons/Conversion.vue'
import DropdownSelector from '@/components/common/DropdownSelector.vue'
import { some } from 'lodash'
const props = defineProps({
decode: {
type: String,
default: decodeTypes.NONE,
},
format: {
type: String,
default: formatTypes.PLAIN_TEXT,
},
disabled: Boolean,
})
const emit = defineEmits(['formatChanged', 'update:decode', 'update:format'])
const onFormatChanged = (selDecode, selFormat) => {
if (!some(decodeTypes, (val) => val === selDecode)) {
selDecode = decodeTypes.NONE
}
if (!some(formatTypes, (val) => val === selFormat)) {
selFormat = formatTypes.PLAIN_TEXT
}
emit('formatChanged', selDecode, selFormat)
if (selDecode !== props.decode) {
emit('update:decode', selDecode)
}
if (selFormat !== props.format) {
emit('update:format', selFormat)
}
}
</script>
<template>
<n-space :size="0" :wrap="false" :wrap-item="false" align="center" justify="start" style="margin-top: 5px">
<dropdown-selector
:default="formatTypes.PLAIN_TEXT"
:disabled="props.disabled"
:icon="Code"
:options="formatTypes"
:tooltip="$t('interface.view_as')"
:value="props.format"
@update:value="(f) => onFormatChanged(props.decode, f)" />
<n-divider vertical />
<dropdown-selector
:default="decodeTypes.NONE"
:disabled="props.disabled"
:icon="Conversion"
:options="decodeTypes"
:tooltip="$t('interface.decode_with')"
:value="props.decode"
@update:value="(d) => onFormatChanged(d, props.format)" />
</n-space>
</template>
<style lang="scss" scoped></style>

View File

@ -1,7 +1,6 @@
<script setup> <script setup>
import { computed, h, reactive, ref, watch } from 'vue' import { computed, h, reactive, ref, watch } from 'vue'
import { types, typesColor } from '@/consts/support_redis_type.js' import { types, typesColor } from '@/consts/support_redis_type.js'
import { decodeTypes, formatTypes } from '@/consts/value_view_type.js'
import useDialog from 'stores/dialog' import useDialog from 'stores/dialog'
import { isEmpty, keys, map } from 'lodash' import { isEmpty, keys, map } from 'lodash'
import NewStringValue from '@/components/new_value/NewStringValue.vue' import NewStringValue from '@/components/new_value/NewStringValue.vue'
@ -117,16 +116,14 @@ const onAdd = async () => {
if (value == null) { if (value == null) {
value = defaultValue[type] value = defaultValue[type]
} }
const { success, msg, nodeKey } = await browserStore.setKey( const { success, msg, nodeKey } = await browserStore.setKey({
server, server,
db, db,
key, key,
type, keyType: type,
value, value,
ttl, ttl,
formatTypes.PLAIN_TEXT, })
decodeTypes.NONE,
)
if (success) { if (success) {
// select current key // select current key
tabStore.setSelectedKeys(server, nodeKey) tabStore.setSelectedKeys(server, nodeKey)

View File

@ -7,6 +7,7 @@
"warning": "Warning", "warning": "Warning",
"error": "Error", "error": "Error",
"save": "Save", "save": "Save",
"update": "Update",
"none": "None", "none": "None",
"second": "Second(s)", "second": "Second(s)",
"unit_day": "D", "unit_day": "D",

View File

@ -7,6 +7,7 @@
"warning": "Aviso", "warning": "Aviso",
"error": "Erro", "error": "Erro",
"save": "Salvar", "save": "Salvar",
"update": "Atualizar",
"none": "Nenhum", "none": "Nenhum",
"second": "Segundo(s)", "second": "Segundo(s)",
"unit_day": "D", "unit_day": "D",

View File

@ -7,6 +7,7 @@
"warning": "警告", "warning": "警告",
"error": "错误", "error": "错误",
"save": "保存", "save": "保存",
"update": "更新",
"none": "无", "none": "无",
"second": "秒", "second": "秒",
"unit_day": "天", "unit_day": "天",

View File

@ -22,6 +22,7 @@ import {
AddZSetValue, AddZSetValue,
CleanCmdHistory, CleanCmdHistory,
CloseConnection, CloseConnection,
ConvertValue,
DeleteKey, DeleteKey,
FlushDB, FlushDB,
GetCmdHistory, GetCmdHistory,
@ -50,6 +51,7 @@ import { KeyViewType } from '@/consts/key_view_type.js'
import { ConnectionType } from '@/consts/connection_type.js' import { ConnectionType } from '@/consts/connection_type.js'
import { types } from '@/consts/support_redis_type.js' import { types } from '@/consts/support_redis_type.js'
import useConnectionStore from 'stores/connections.js' import useConnectionStore from 'stores/connections.js'
import { decodeTypes, formatTypes } from '@/consts/value_view_type.js'
const useBrowserStore = defineStore('browser', { const useBrowserStore = defineStore('browser', {
/** /**
@ -482,6 +484,24 @@ const useBrowserStore = defineStore('browser', {
} }
}, },
/**
* convert value by decode type or format
* @param {string|number[]} value
* @param {string} [decode]
* @param {string} [format]
* @return {Promise<{[format]: string, [decode]: string, value: string}>}
*/
async convertValue({ value, decode, format }) {
try {
const { data, success } = await ConvertValue(value, decode, format)
if (success) {
const { value: retVal, decode: retDecode, format: retFormat } = data
return { value: retVal, decode: retDecode, format: retFormat }
}
} catch (e) {}
return { value, decode, format }
},
/** /**
* scan keys with prefix * scan keys with prefix
* @param {string} connName * @param {string} connName
@ -929,27 +949,50 @@ const useBrowserStore = defineStore('browser', {
/** /**
* set redis key * set redis key
* @param {string} connName * @param {string} server
* @param {number} db * @param {number} db
* @param {string|number[]} key * @param {string|number[]} key
* @param {string} keyType * @param {string} keyType
* @param {any} value * @param {any} value
* @param {number} ttl * @param {number} ttl
* @param {string} [viewAs] * @param {string} [format]
* @param {string} [decode] * @param {string} [decode]
* @returns {Promise<{[msg]: string, success: boolean, [nodeKey]: {string}}>} * @returns {Promise<{[msg]: string, success: boolean, [nodeKey]: {string}}>}
*/ */
async setKey(connName, db, key, keyType, value, ttl, viewAs, decode) { async setKey({
server,
db,
key,
keyType,
value,
ttl,
format = formatTypes.PLAIN_TEXT,
decode = decodeTypes.NONE,
}) {
try { try {
const { data, success, msg } = await SetKeyValue(connName, db, key, keyType, value, ttl, viewAs, decode) const { data, success, msg } = await SetKeyValue({
server,
db,
key,
keyType,
value,
ttl,
format,
decode,
})
if (success) { if (success) {
const { value } = data
// update tree view data // update tree view data
const { newKey = 0 } = this._addKeyNodes(connName, db, [key], true) const { newKey = 0 } = this._addKeyNodes(server, db, [key], true)
if (newKey > 0) { if (newKey > 0) {
this._tidyNode(connName, db, key) this._tidyNode(server, db, key)
this._updateDBMaxKeys(connName, db, newKey) this._updateDBMaxKeys(server, db, newKey)
}
return {
success,
nodeKey: `${server}/db${db}#${ConnectionType.RedisValue}/${key}`,
updatedValue: value,
} }
return { success, nodeKey: `${connName}/db${db}#${ConnectionType.RedisValue}/${key}` }
} else { } else {
return { success, msg } return { success, msg }
} }
@ -959,30 +1002,54 @@ const useBrowserStore = defineStore('browser', {
}, },
/** /**
* update hash field * update hash entry
* when field is set, newField is null, delete field * when field is set, newField is null, delete field
* when field is null, newField is set, add new field * when field is null, newField is set, add new field
* when both field and newField are set, and field === newField, update field * when both field and newField are set, and field === newField, update field
* when both field and newField are set, and field !== newField, delete field and add newField * when both field and newField are set, and field !== newField, delete field and add newField
* @param {string} connName * @param {string} server
* @param {number} db * @param {number} db
* @param {string|number[]} key * @param {string|number[]} key
* @param {string} field * @param {string} field
* @param {string} newField * @param {string} [newField]
* @param {string} value * @param {string} [value]
* @param {string} [decode]
* @param {string} [format]
* @param {boolean} [refresh]
* @returns {Promise<{[msg]: string, success: boolean, [updated]: {}}>} * @returns {Promise<{[msg]: string, success: boolean, [updated]: {}}>}
*/ */
async setHash(connName, db, key, field, newField, value) { async setHash({
server,
db,
key,
field,
newField = '',
value = '',
decode = decodeTypes.NONE,
format = formatTypes.PLAIN_TEXT,
refresh,
}) {
try { try {
const { data, success, msg } = await SetHashValue(connName, db, key, field, newField || '', value || '') const { data, success, msg } = await SetHashValue({
server,
db,
key,
field,
newField,
value,
decode,
format,
})
if (success) { if (success) {
const { updated = {}, removed = [], replaced = {} } = data const { updated = {}, removed = [], replaced = {} } = data
const tab = useTabStore() if (refresh === true) {
if (!isEmpty(removed)) { const tab = useTabStore()
tab.removeValueEntries({ server: connName, db, key, type: 'hash', entries: removed }) if (!isEmpty(removed)) {
} tab.removeValueEntries({ server, db, key, type: 'hash', entries: removed })
if (!isEmpty(updated)) { }
tab.upsertValueEntries({ server: connName, db, key, type: 'hash', entries: updated }) if (!isEmpty(updated)) {
tab.upsertValueEntries({ server, db, key, type: 'hash', entries: updated })
}
} }
return { success, updated } return { success, updated }
} else { } else {

View File

@ -57,6 +57,10 @@ export const themeOverrides = {
Message: { Message: {
margin: '0 0 38px 0', margin: '0 0 38px 0',
}, },
DataTable: {
thPaddingSmall: '6px 8px',
tdPaddingSmall: '6px 8px',
},
} }
/** /**