forked from postalsys/imapflow
/
create.ts
83 lines (69 loc) · 2.44 KB
/
create.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import { encodePath, normalizePath, getStatusCode, getErrorText } from '../tools.js';
// Creates a new mailbox
export const CREATE = async (connection, path) => {
if (![connection.states.AUTHENTICATED, connection.states.SELECTED].includes(connection.state)) {
// nothing to do here
return;
}
path = normalizePath(connection, path);
let response;
try {
let map = {
path
};
response = await connection.exec('CREATE', [{ type: 'ATOM', value: encodePath(connection, path) }]);
let section =
response.response.attributes &&
response.response.attributes[0] &&
response.response.attributes[0].section &&
response.response.attributes[0].section.length
? response.response.attributes[0].section
: false;
if (section) {
let key;
section.forEach((attribute, i) => {
if (i % 2 === 0) {
key = attribute && typeof attribute.value === 'string' ? attribute.value : false;
return;
}
if (!key) {
return;
}
let value;
switch (key.toLowerCase()) {
case 'mailboxid':
key = 'mailboxId';
value = Array.isArray(attribute) && attribute[0] && typeof attribute[0].value === 'string' ? attribute[0].value : false;
break;
}
if (key && value) {
map[key] = value;
}
});
}
map.created = true;
response.next();
//make sure we are subscribed to the new folder as well
await connection.run('SUBSCRIBE', path);
return map;
} catch (err) {
let errorCode = getStatusCode(err.response);
if (errorCode) {
err.serverResponseCode = errorCode;
}
err.response = await getErrorText(err.response);
switch (errorCode) {
case 'ALREADYEXISTS':
// no need to do anything, mailbox already exists
return {
path,
created: false
};
}
if (errorCode) {
err.serverResponseCode = errorCode;
}
connection.log.warn({ err, cid: connection.id });
throw err;
}
};