1/**
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15import SearchData from '../model/SearchData';
16import Log from '../../../../../../utils/src/main/ets/default/baseUtil/LogDecorator';
17import ResourceUtil from './ResourceUtil';
18
19/**
20 * Search util
21 */
22export class SearchUtil {
23
24  /**
25   * Convert json to instance
26   */
27  @Log
28  convertJsonToInstance<T> (json: any, t: {new(): T}): T {
29    var instance = new t();
30
31    for (var key in json) {
32      if (instance.hasOwnProperty(key)) {
33        instance[key] = json[key];
34      }
35    }
36
37    return instance;
38  }
39
40  /**
41   * Convert json to SearchData instance
42   */
43  @Log
44  async convertToSearchData(rawData): Promise<SearchData[]> {
45    let result: Array<SearchData> = [];
46
47    for (let jsonData of rawData.data) {
48      let searchData: SearchData = new SearchData();
49      searchData.title = await ResourceUtil.getString(rawData.title);
50      searchData.keyword = await ResourceUtil.getString(jsonData.keyword);
51      searchData.summary = jsonData.summary ? await ResourceUtil.getString(jsonData.summary) : jsonData.summary;
52      searchData.synonym = jsonData.synonym ? await ResourceUtil.getString(jsonData.synonym) : jsonData.synonym;
53
54      result.push(searchData);
55    };
56
57    return result;
58  }
59
60  /**
61   * Delete illegal characters from search keyword
62   *
63   * @param text
64   */
65  stripKeyword(text: string): string  {
66    var pattern = new RegExp("[`~!@#$%^&*()=|{}':;',\\[\\].<>/?~!@#¥……&*()——|{}【】‘;:”“'。,、?]")
67    var rs = "";
68    for (var i = 0; i < text.length; i++) {
69      rs = rs + text.substr(i, 1).replace(pattern, '');
70    }
71    return rs;
72  }
73
74}
75
76let searchUtil = new SearchUtil();
77export default searchUtil as SearchUtil;
78