1/*
2 * Copyright (c) 2022 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 */
15const URI_SPLIT = '/';
16
17const ERROR_CODE_INVALID_PARAM = 401;
18const ERROR_CODE_INNER_ERROR = 16000050;
19
20const ERROR_MSG_INVALID_PARAM = 'Invalid input parameter.';
21const ERROR_MSG_INNER_ERROR = 'Inner Error.';
22
23let errMap = new Map();
24errMap.set(ERROR_CODE_INVALID_PARAM, ERROR_MSG_INVALID_PARAM);
25errMap.set(ERROR_CODE_INNER_ERROR, ERROR_MSG_INNER_ERROR);
26
27class DataUriError extends Error {
28  constructor(code) {
29    let msg = '';
30    if (errMap.has(code)) {
31      msg = errMap.get(code);
32    } else {
33      msg = ERROR_MSG_INNER_ERROR;
34    }
35    super(msg);
36    this.code = code;
37  }
38}
39
40let dataUriUtils = {
41  getId: (uri) => {
42    console.debug('DataUriUtils getId called.');
43    if (typeof uri !== 'string') {
44      throw new DataUriError(ERROR_CODE_INVALID_PARAM);
45    }
46    let index = uri.lastIndexOf(URI_SPLIT);
47    if (index === -1) {
48      throw new DataUriError(ERROR_CODE_INVALID_PARAM);
49    }
50    let ret = uri.substring(index + 1);
51    if (ret === '' || isNaN(Number(ret))) {
52      throw new DataUriError(ERROR_CODE_INVALID_PARAM);
53    }
54    return Number(ret);
55  },
56  updateId: (uri, id) => {
57    console.debug('DataUriUtils updateId called.');
58    if (typeof uri !== 'string' || typeof id !== 'number') {
59      throw new DataUriError(ERROR_CODE_INVALID_PARAM);
60    }
61    let ret = dataUriUtils.deleteId(uri);
62    if (ret === uri) {
63      throw new DataUriError(ERROR_CODE_INVALID_PARAM);
64    }
65    return ret + URI_SPLIT + id;
66  },
67  deleteId: (uri) => {
68    console.debug('DataUriUtils deleteId called.');
69    if (typeof uri !== 'string') {
70      throw new DataUriError(ERROR_CODE_INVALID_PARAM);
71    }
72    let index = uri.lastIndexOf(URI_SPLIT);
73    if (index === -1) {
74      throw new DataUriError(ERROR_CODE_INVALID_PARAM);
75    }
76    let id = uri.substring(index + 1);
77    if (id === '' || isNaN(Number(id))) {
78      throw new DataUriError(ERROR_CODE_INVALID_PARAM);
79    }
80    return uri.substring(0, index);
81  },
82  attachId: (uri, id) => {
83    console.debug('DataUriUtils attachId called.');
84    if (typeof uri !== 'string' || typeof id !== 'number') {
85      throw new DataUriError(ERROR_CODE_INVALID_PARAM);
86    }
87    return uri + URI_SPLIT + id;
88  }
89};
90
91export default dataUriUtils;