1// Copyright (C) 2020 The Android Open Source Project
2//
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 {createEmptyRecordConfig, RecordConfig} from '../common/state';
16
17interface RecordConfigValidationResult {
18  config: RecordConfig;
19  errorMessage?: string;
20}
21
22export function validateRecordConfig(
23    config: {[key: string]: string|number|boolean|string[]|null}):
24    RecordConfigValidationResult {
25  // Remove the keys that are not in both createEmptyRecordConfig and
26  // config.
27  const newConfig: RecordConfig = createEmptyRecordConfig();
28  const ignoredKeys: string[] = [];
29  // TODO(bsebastien): Also check that types of properties match.
30  Object.entries(newConfig).forEach(([key, value]) => {
31    if (key in config && typeof value === typeof config[key]) {
32      newConfig[key] = config[key];
33    } else {
34      ignoredKeys.push(key);
35    }
36  });
37
38  // Check if config has additional keys that are not in
39  // createEmptyRecordConfig().
40  for (const key of Object.keys(config)) {
41    if (!(key in newConfig)) {
42      ignoredKeys.push(key);
43    }
44  }
45
46  if (ignoredKeys.length > 0) {
47    // At least return an empty RecordConfig if nothing match.
48    return {
49      errorMessage: 'Warning: Loaded config contains incompatible keys.\n\
50        It may have been created with an older version of the UI.\n\
51        Ignored keys: ' +
52          ignoredKeys.join(' '),
53      config: newConfig,
54    };
55  }
56  return {config: newConfig};
57}
58