Create new search query parser
[arvados-workbench2.git] / src / store / search-bar / search-query / arv-parser.ts
1
2 // Copyright (C) The Arvados Authors. All rights reserved.
3 //
4 // SPDX-License-Identifier: AGPL-3.0
5
6 import * as parser from '~/store/search-bar/search-query/parser';
7
8 interface Property {
9     key: string;
10     value: string;
11 }
12
13 export enum Keywords {
14     TYPE = 'type',
15     CLUSTER = 'cluster',
16     PROJECT = 'project',
17     IS = 'is',
18     FROM = 'from',
19     TO = 'to',
20 }
21
22 const keyValuePattern = (key: string) => new RegExp(`${key}:([^ ]*)`);
23 const propertyPattern = /has:"(.*?)":"(.*?)"/;
24
25 const patterns = [
26     keyValuePattern(Keywords.TYPE),
27     keyValuePattern(Keywords.CLUSTER),
28     keyValuePattern(Keywords.PROJECT),
29     keyValuePattern(Keywords.IS),
30     keyValuePattern(Keywords.FROM),
31     keyValuePattern(Keywords.TO),
32     propertyPattern
33 ];
34
35 export const parseSearchQuery = parser.parseSearchQuery(patterns);
36
37 export const getValue = (tokens: string[]) => (key: string) => {
38     const pattern = keyValuePattern(key);
39     const token = tokens.find(t => pattern.test(t));
40     if (token) {
41         const [, value] = token.split(':');
42         return value;
43     }
44     return undefined;
45 };
46
47 export const getProperties = (tokens: string[]) =>
48     tokens.reduce((properties, token) => {
49         const match = token.match(propertyPattern);
50         if (match) {
51             const [, key, value] = match;
52             const newProperty = { key, value };
53             return [...properties, newProperty];
54         }
55         return properties;
56     }, [] as Property[]);