File size: 1,778 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { pickBy } from 'lodash';

export const toAuthor = ( { avatar_URL, email, ID, name } ) => {
	if ( ID > 0 ) {
		return {
			kind: 'known',
			userId: parseInt( ID, 10 ),
		};
	}

	return Object.assign(
		{ kind: 'anonymous' },
		avatar_URL && { avatar: avatar_URL },
		email && { email },
		name && { displayName: name }
	);
};

export const toWpcomUser = ( author ) =>
	pickBy(
		{
			ID: author.ID,
			avatar_URL: author.avatarURL,
			display_name: author.name,
			email: author.email,
			primary_blog: author.site_ID,
			primary_blog_url: author.URL,
			username: author.login,
		},
		( a ) => !! a
	);

export const validStatusValues = {
	approved: 'approved',
	spam: 'spam',
	trash: 'trash',
	unapproved: 'pending',
};

/**
 * Attempts to parse a response from the comment endpoint
 * and return the mapped comment object with its author
 * @param {number} siteId site id is not included in the response items
 * @param {Object} data raw comment data from API
 * @returns {Object} comment and WordPress.com user if available
 */
export const fromApi = ( siteId, data ) => {
	try {
		return Object.assign(
			{
				comment: Object.assign(
					{
						state: 'loaded',
						author: toAuthor( data.author ),
						commentId: parseInt( data.ID, 10 ),
						content: data.content,
						createdAt: Date.parse( data.date ),
						isLiked: Boolean( data.i_like ),
					},
					data.parent &&
						data.parent.type === 'comment' && { parentId: parseInt( data.parent.ID, 10 ) },
					{
						postId: parseInt( data.post.ID, 10 ),
						siteId,
						status: validStatusValues[ data.status ],
					}
				),
			},
			data.author.ID > 0 && { user: toWpcomUser( data.author ) }
		);
	} catch ( e ) {
		return {
			state: 'error',
			error: 'invalid data structure',
		};
	}
};