PluginProbe
Code Snippets / 3.7.0
Code Snippets v3.7.0
3.10.2 3.10.1 3.10.0 3.10.0-beta.2 3.10.0-beta.1 4.0.0-beta.1 3.9.6 trunk 2.10.0 2.10.1 2.12.0 2.12.1 2.13.0 2.13.1 2.13.2 2.13.3 2.14.0 2.14.1 2.14.2 2.14.3 2.14.4 2.14.5 2.14.6 3.0.0 3.0.1 All 64 releases
code-snippets / js / utils / snippets / objects.ts

objects.ts in Code Snippets 3.7.0, at js/utils/snippets/objects.ts

52 lines 2.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 import { SNIPPET_TYPE_SCOPES } from '../../types/Snippet'
2 import { isNetworkAdmin } from '../screen'
3 import type { Snippet, SnippetScope } from '../../types/Snippet'
4
5 const defaults: Omit<Snippet, 'tags'> = {
6 id: 0,
7 name: '',
8 code: '',
9 desc: '',
10 scope: 'global',
11 modified: '',
12 active: false,
13 network: isNetworkAdmin(),
14 shared_network: null,
15 priority: 10,
16 conditionId: 0
17 }
18
19 const isAbsInt = (value: unknown): value is number =>
20 'number' === typeof value && 0 < value
21
22 const parseStringArray = (value: unknown): string[] | undefined =>
23 Array.isArray(value) ? value.filter(entry => 'string' === typeof entry) : undefined
24
25 export const isValidScope = (scope: unknown): scope is SnippetScope =>
26 'string' === typeof scope && Object.values(SNIPPET_TYPE_SCOPES).some(typeScopes =>
27 typeScopes.some(typeScope => typeScope === scope))
28
29 export const parseSnippetObject = (fields: unknown): Snippet => {
30 const result: { -readonly [F in keyof Snippet]: Snippet[F] } = { ...defaults, tags: [] }
31
32 if ('object' !== typeof fields || null === fields) {
33 return result
34 }
35
36 return {
37 ...result,
38 ...'id' in fields && isAbsInt(fields.id) && { id: fields.id },
39 ...'name' in fields && 'string' === typeof fields.name && { name: fields.name },
40 ...'desc' in fields && 'string' === typeof fields.desc && { desc: fields.desc },
41 ...'code' in fields && 'string' === typeof fields.code && { code: fields.code },
42 ...'tags' in fields && { tags: parseStringArray(fields.tags) ?? result.tags },
43 ...'scope' in fields && isValidScope(fields.scope) && { scope: fields.scope },
44 ...'modified' in fields && 'string' === typeof fields.modified && { modified: fields.modified },
45 ...'active' in fields && 'boolean' === typeof fields.active && { active: fields.active },
46 ...'network' in fields && 'boolean' === typeof fields.network && { network: fields.network },
47 ...'shared_network' in fields && 'boolean' === typeof fields.shared_network && { shared_network: fields.shared_network },
48 ...'priority' in fields && 'number' === typeof fields.priority && { priority: fields.priority },
49 ...'condition_id' in fields && isAbsInt(fields.condition_id) && { conditionId: fields.condition_id }
50 }
51 }
52