-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathchannels.js
More file actions
110 lines (90 loc) · 2.52 KB
/
channels.js
File metadata and controls
110 lines (90 loc) · 2.52 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/**
* Channel management controller
* @module controllers/channels
*/
import { IndiekitError } from "@indiekit/error";
import {
getChannels,
createChannel,
updateChannel,
deleteChannel,
reorderChannels,
} from "../storage/channels.js";
import { getUserId } from "../utils/auth.js";
import {
validateChannel,
validateChannelName,
parseArrayParameter,
} from "../utils/validation.js";
/**
* List all channels
* GET ?action=channels
* @param {object} request - Express request
* @param {object} response - Express response
*/
export async function list(request, response) {
const { application } = request.app.locals;
const userId = getUserId(request);
const channels = await getChannels(application, userId);
response.json({ channels });
}
/**
* Handle channel actions (create, update, delete, order)
* POST ?action=channels
* @param {object} request - Express request
* @param {object} response - Express response
* @returns {Promise<void>}
*/
export async function action(request, response) {
const { application } = request.app.locals;
const userId = getUserId(request);
const { method, name, uid } = request.body;
// Delete channel
if (method === "delete") {
validateChannel(uid);
const deleted = await deleteChannel(application, uid, userId);
if (!deleted) {
throw new IndiekitError("Channel not found or cannot be deleted", {
status: 404,
});
}
return response.json({ deleted: uid });
}
// Reorder channels
if (method === "order") {
const channelUids = parseArrayParameter(request.body, "channels");
if (channelUids.length === 0) {
throw new IndiekitError("Missing channels[] parameter", {
status: 400,
});
}
await reorderChannels(application, channelUids, userId);
const channels = await getChannels(application, userId);
return response.json({ channels });
}
// Update existing channel
if (uid) {
validateChannel(uid);
if (name) {
validateChannelName(name);
}
const channel = await updateChannel(application, uid, { name }, userId);
if (!channel) {
throw new IndiekitError("Channel not found", {
status: 404,
});
}
return response.json({
uid: channel.uid,
name: channel.name,
});
}
// Create new channel
validateChannelName(name);
const channel = await createChannel(application, { name, userId });
response.status(201).json({
uid: channel.uid,
name: channel.name,
});
}
export const channelsController = { list, action };