directus

Форк
0
/
activity.ts 
183 строки · 4.1 Кб
1
import { Action } from '@directus/constants';
2
import { isDirectusError } from '@directus/errors';
3
import express from 'express';
4
import Joi from 'joi';
5
import { ErrorCode, ForbiddenError, InvalidPayloadError } from '@directus/errors';
6
import { respond } from '../middleware/respond.js';
7
import useCollection from '../middleware/use-collection.js';
8
import { validateBatch } from '../middleware/validate-batch.js';
9
import { ActivityService } from '../services/activity.js';
10
import { MetaService } from '../services/meta.js';
11
import asyncHandler from '../utils/async-handler.js';
12
import { getIPFromReq } from '../utils/get-ip-from-req.js';
13

14
const router = express.Router();
15

16
router.use(useCollection('directus_activity'));
17

18
const readHandler = asyncHandler(async (req, res, next) => {
19
	const service = new ActivityService({
20
		accountability: req.accountability,
21
		schema: req.schema,
22
	});
23

24
	const metaService = new MetaService({
25
		accountability: req.accountability,
26
		schema: req.schema,
27
	});
28

29
	let result;
30

31
	if (req.singleton) {
32
		result = await service.readSingleton(req.sanitizedQuery);
33
	} else if (req.body.keys) {
34
		result = await service.readMany(req.body.keys, req.sanitizedQuery);
35
	} else {
36
		result = await service.readByQuery(req.sanitizedQuery);
37
	}
38

39
	const meta = await metaService.getMetaForQuery('directus_activity', req.sanitizedQuery);
40

41
	res.locals['payload'] = {
42
		data: result,
43
		meta,
44
	};
45

46
	return next();
47
});
48

49
router.search('/', validateBatch('read'), readHandler, respond);
50
router.get('/', readHandler, respond);
51

52
router.get(
53
	'/:pk',
54
	asyncHandler(async (req, res, next) => {
55
		const service = new ActivityService({
56
			accountability: req.accountability,
57
			schema: req.schema,
58
		});
59

60
		const record = await service.readOne(req.params['pk']!, req.sanitizedQuery);
61

62
		res.locals['payload'] = {
63
			data: record || null,
64
		};
65

66
		return next();
67
	}),
68
	respond,
69
);
70

71
const createCommentSchema = Joi.object({
72
	comment: Joi.string().required(),
73
	collection: Joi.string().required(),
74
	item: [Joi.number().required(), Joi.string().required()],
75
});
76

77
router.post(
78
	'/comment',
79
	asyncHandler(async (req, res, next) => {
80
		const service = new ActivityService({
81
			accountability: req.accountability,
82
			schema: req.schema,
83
		});
84

85
		const { error } = createCommentSchema.validate(req.body);
86

87
		if (error) {
88
			throw new InvalidPayloadError({ reason: error.message });
89
		}
90

91
		const primaryKey = await service.createOne({
92
			...req.body,
93
			action: Action.COMMENT,
94
			user: req.accountability?.user,
95
			ip: getIPFromReq(req),
96
			user_agent: req.accountability?.userAgent,
97
			origin: req.get('origin'),
98
		});
99

100
		try {
101
			const record = await service.readOne(primaryKey, req.sanitizedQuery);
102

103
			res.locals['payload'] = {
104
				data: record || null,
105
			};
106
		} catch (error: any) {
107
			if (isDirectusError(error, ErrorCode.Forbidden)) {
108
				return next();
109
			}
110

111
			throw error;
112
		}
113

114
		return next();
115
	}),
116
	respond,
117
);
118

119
const updateCommentSchema = Joi.object({
120
	comment: Joi.string().required(),
121
});
122

123
router.patch(
124
	'/comment/:pk',
125
	asyncHandler(async (req, res, next) => {
126
		const service = new ActivityService({
127
			accountability: req.accountability,
128
			schema: req.schema,
129
		});
130

131
		const { error } = updateCommentSchema.validate(req.body);
132

133
		if (error) {
134
			throw new InvalidPayloadError({ reason: error.message });
135
		}
136

137
		const primaryKey = await service.updateOne(req.params['pk']!, req.body);
138

139
		try {
140
			const record = await service.readOne(primaryKey, req.sanitizedQuery);
141

142
			res.locals['payload'] = {
143
				data: record || null,
144
			};
145
		} catch (error: any) {
146
			if (isDirectusError(error, ErrorCode.Forbidden)) {
147
				return next();
148
			}
149

150
			throw error;
151
		}
152

153
		return next();
154
	}),
155
	respond,
156
);
157

158
router.delete(
159
	'/comment/:pk',
160
	asyncHandler(async (req, _res, next) => {
161
		const service = new ActivityService({
162
			accountability: req.accountability,
163
			schema: req.schema,
164
		});
165

166
		const adminService = new ActivityService({
167
			schema: req.schema,
168
		});
169

170
		const item = await adminService.readOne(req.params['pk']!, { fields: ['action'] });
171

172
		if (!item || item['action'] !== Action.COMMENT) {
173
			throw new ForbiddenError();
174
		}
175

176
		await service.deleteOne(req.params['pk']!);
177

178
		return next();
179
	}),
180
	respond,
181
);
182

183
export default router;
184

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.