-
Notifications
You must be signed in to change notification settings - Fork 0
/
nfc.ts
51 lines (48 loc) · 1.19 KB
/
nfc.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
let ndef: any = null;
try {
// @ts-ignore
ndef = new NDEFReader();
} catch {
document.documentElement.classList.add('ndef-disabled');
}
interface NDEFRecord {
recordType: string;
data: AllowSharedBufferSource;
encoding: string;
toRecords(): Iterable<NDEFRecord>;
}
function expandRecord(parent: NDEFRecord): Record<string, any> {
try {
const result = {};
for (const child of parent.toRecords()) {
const data = expandRecord(child);
for (let [key, value] of Object.entries(data)) {
result[key] = (key in result)
? [result[key], value].flat()
: result[key] = value;
}
}
return { [parent.recordType]: result };
} catch {
const { recordType, data, encoding } = parent;
return {
[recordType]: new TextDecoder(encoding ?? 'utf-8').decode(data)
};
}
}
export function getData(signal?: AbortSignal): Promise<any> {
return new Promise(async (resolve, reject) => {
try {
await ndef.scan({ signal });
ndef.addEventListener('reading', ({ message }) => {
resolve(
Array.from(message.records)
.map(expandRecord)
.reduce<Record<string, any>>((obj, expanded) => Object.assign(obj, expanded), {})
);
});
} catch(err) {
reject(err);
}
});
}