1
/*
2
 * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
5
 * the License. A copy of the License is located at
6
 *
7
 *     http://aws.amazon.com/apache2.0/
8
 *
9
 * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
10
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
11
 * and limitations under the License.
12
 */
13

14
import { CacheConfig, CacheItem, CacheItemOptions } from '../types';
15 1
import { StorageHelper } from '@aws-amplify/core';
16
/**
17
 * Default cache config
18
 */
19 1
export const defaultConfig: CacheConfig = {
20
	keyPrefix: 'aws-amplify-cache',
21
	capacityInBytes: 1048576, // 1MB
22
	itemMaxSize: 210000, // about 200kb
23
	defaultTTL: 259200000, // about 3 days
24
	defaultPriority: 5,
25
	warningThreshold: 0.8,
26
	// the storage helper will check if localStorage exists,
27
	// if not, will use a in-memory object instead
28
	storage: new StorageHelper().getStorage(),
29
};
30

31
/**
32
 * return the byte size of the string
33
 * @param str
34
 */
35 1
export function getByteLength(str: string): number {
36 1
	let ret: number = 0;
37 1
	ret = str.length;
38

39 1
	for (let i = str.length; i >= 0; i -= 1) {
40 1
		const charCode: number = str.charCodeAt(i);
41 1
		if (charCode > 0x7f && charCode <= 0x7ff) {
42 1
			ret += 1;
43 1
		} else if (charCode > 0x7ff && charCode <= 0xffff) {
44 1
			ret += 2;
45
		}
46
		// trail surrogate
47 1
		if (charCode >= 0xdc00 && charCode <= 0xdfff) {
48 0
			i -= 1;
49
		}
50
	}
51

52 1
	return ret;
53
}
54

55
/**
56
 * get current time
57
 */
58 1
export function getCurrTime(): number {
59 1
	const currTime = new Date();
60 1
	return currTime.getTime();
61
}
62

63
/**
64
 * check if passed value is an integer
65
 */
66 1
export function isInteger(value): boolean {
67 1
	if (Number.isInteger) {
68 1
		return Number.isInteger(value);
69
	}
70

71 0
	return _isInteger(value);
72
}
73

74
function _isInteger(value): boolean {
75 0
	return (
76 1
		typeof value === 'number' && isFinite(value) && Math.floor(value) === value
77
	);
78
}
79

80
/**
81
 * provide an object as the in-memory cache
82
 */
83 1
let store = {};
84 1
export class CacheObject {
85 1
	static clear(): void {
86 0
		store = {};
87
	}
88

89 1
	static getItem(key: string): string | null {
90 1
		return store[key] || null;
91
	}
92

93 1
	static setItem(key: string, value: string): void {
94 1
		store[key] = value;
95
	}
96

97 1
	static removeItem(key: string): void {
98 1
		delete store[key];
99
	}
100 1
}

Read our documentation on viewing source code .

Loading