UNPKG

1.27 kBPlain TextView Raw
1import { DEBUG } from '@glimmer/env';
2
3// Used by the store to normalize IDs entering the store. Despite the fact
4// that developers may provide IDs as numbers (e.g., `store.findRecord('person', 1)`),
5// it is important that internally we use strings, since IDs may be serialized
6// and lose type information. For example, Ember's router may put a record's
7// ID into the URL, and if we later try to deserialize that URL and find the
8// corresponding record, we will not know if it is a string or a number.
9type Coercable = string | number | boolean | null | undefined | symbol;
10
11function coerceId(id: Coercable): string | null {
12 if (id === null || id === undefined || id === '') {
13 return null;
14 }
15 if (typeof id === 'string') {
16 return id;
17 }
18 if (typeof id === 'symbol') {
19 return id.toString();
20 }
21 return '' + id;
22}
23
24export function ensureStringId(id: Coercable): string {
25 let normalized: string | null = null;
26 if (typeof id === 'string') {
27 normalized = id.length > 0 ? id : null;
28 } else if (typeof id === 'number' && !isNaN(id)) {
29 normalized = '' + id;
30 }
31
32 if (DEBUG && normalized === null) {
33 throw new Error(`Expected id to be a string or number, received ${String(id)}`);
34 }
35
36 return normalized!;
37}
38
39export default coerceId;