FastComments.com

La API de FastComments

FastComments proporciona una API para interactuar con muchos recursos. Crea integraciones con nuestra plataforma, ¡o incluso desarrolla tus propios clientes!

En esta documentación encontrarás todos los recursos compatibles por la API documentados con sus tipos de solicitud y respuesta.

Para clientes Enterprise, todo el acceso a la API queda registrado en el Registro de Auditoría.

SDKs Generados

FastComments ahora genera una Especificación de la API a partir de nuestro código (esto aún no está completo, pero incluye muchas APIs).

También ahora tenemos SDKs para lenguajes populares:

Autenticación

La API se autentica pasando tu clave API ya sea como un encabezado X-API-KEY o como un parámetro de consulta API_KEY. También necesitarás tu tenantId para realizar llamadas a la API. Esto puede obtenerse desde la misma página que tu clave API.

Nota de seguridad

Estas rutas están pensadas para ser llamadas desde un servidor. NO las llames desde un navegador. Hacerlo expondrá tu clave API - esto proporcionará acceso total a tu cuenta a cualquiera que pueda ver el código fuente de una página!

Opción de autenticación uno - Encabezados

  • Encabezado: X-API-KEY
  • Encabezado: X-TENANT-ID

Opción de autenticación dos - Parámetros de consulta

  • Parámetro de consulta: API_KEY
  • Parámetro de consulta: tenantId

Estructura de registro de auditoría Internal Link

Un AuditLog es un objeto que representa un evento auditado para inquilinos que tienen acceso a esta función.

La estructura para el objeto AuditLog es la siguiente:

Estructura de AuditLog
Copy Copy
1
2interface AuditLog {
3 id: string;
4 userId?: string;
5 username?: string;
6 resourceName: string;
7 crudType: 'c' | 'r' | 'u' | 'd' | 'login';
8 from: string;
9 url?: string;
10 ip?: string;
11 when: string;
12 description?: string;
13 serverStartDate: string;
14 objectDetails?: object;
15}
16

El registro de auditoría es inmutable. Tampoco se puede escribir manualmente. FastComments.com es el único que puede decidir cuándo escribir en el registro de auditoría. Sin embargo, puede leer de él a través de esta API.

Los eventos en el registro de auditoría expiran después de dos años.

Estructura de comentario Internal Link

Un objeto Comment representa un comentario dejado por un usuario.

La relación entre comentarios padre e hijo se define a través de parentId.

La estructura para el objeto Comment es la siguiente:

Estructura de Comment
Copy Copy
1
2interface Comment {
3 /** READONLY: Set to true if the spam engine determined the comment was spam. **/
4 aiDeterminedSpam?: boolean
5 /** Whether the comment is approved to show. Set to true when saving the comment, else it will be hidden. **/
6 approved?: boolean
7 /** The user's avatar. **/
8 avatarSrc?: string
9 /** Child comments. Not populated in all scenarios. Used when asTree is set to true via the API. **/
10 children: Comment[]
11 /** The commenter's raw comment. **/
12 comment: string
13 /** READONLY: The commenter's comment parsed into HTML. **/
14 commentHTML?: string
15 /** The commenter's email. Required if anonymous commenting is off. **/
16 commenterEmail?: string
17 /** The commenter's link (for example, their blog). **/
18 commenterLink?: string
19 /** The commenter's name. Always required. If not available, set to something like "Anonymous". **/
20 commenterName: string
21 /** The date the comment was left, in UTC epoch. **/
22 date: number
23 /** The "display label" for the comment - for example "Admin", "Moderator", or something like "VIP User". **/
24 displayLabel?: string
25 /** The domain the comment was posted on. **/
26 domain?: string
27 /** READONLY: The number of times the comment was flagged. **/
28 flagCount?: number
29 /** The #hashtags written in the comment that were successfully parsed. You can also manually add hashtags, for querying, but they won't display in the comment text automatically. **/
30 hashTags?: CommentHashTag[]
31 /** READONLY: Does the comment contain images? **/
32 hasImages?: boolean
33 /** READONLY: Does the comment contain links? **/
34 hasLinks?: boolean
35 /** READONLY: The unique comment id. **/
36 id: string
37 /** Only on create! This is hashed for storage. **/
38 ip?: string
39 /** READONLY: Did the current user block the user that wrote this comment? **/
40 isBlocked?: boolean
41 /** READONLY: Is the comment by an admin? Automatically set based on userId. **/
42 isByAdmin?: boolean
43 /** READONLY: Is the comment by a moderator? Automatically set based on userId. **/
44 isByModerator?: boolean
45 /** Set to true if the comment was soft deleted (placeholder had to be left due to some other configuration). **/
46 isDeleted?: boolean
47 /** Set to true if the user's account was deleted and the comment had to be retained. **/
48 isDeletedUser?: boolean
49 /** READONLY: Is the flagged by the currently logged-in user (contextUserId)? **/
50 isFlagged?: boolean
51 /** Is the comment pinned? **/
52 isPinned?: boolean
53 /** Is the comment locked for new replies (moderators still can reply)? **/
54 isLocked?: boolean
55 /** Is the comment spam? **/
56 isSpam?: boolean
57 /** READONLY: Is the comment voted down for the current user (contextUserId)? **/
58 isVotedDown?: boolean
59 /** READONLY: Is the comment voted up for the current user (contextUserId)? **/
60 isVotedUp?: boolean
61 /** The locale the comment is in. If not provided, will be derived from the language accept HTTP header. **/
62 locale?: 'de_de' | 'en_us' | 'es_es' | 'fr_fr' | 'it_it' | 'ja_jp' | 'ko_kr' | 'pl_pl' | 'pt_br' | 'ru_ru' | 'tr_tr' | 'zh_cn' | 'zh_tw'
63 /** READONLY: The @mentions written in the comment that were successfully parsed. **/
64 mentions?: CommentUserMention[]
65 /** Optional metadata associated with the comment. **/
66 meta?: Record<string, string | number | boolean>
67 /** The optional list of moderation group ids associated with this comment. **/
68 moderationGroupIds?: string[]|null
69 /** READONLY: The id of the vote object that corresponds to the vote from the current user (contextUserId) on this comment. **/
70 myVoteId?: string
71 /** Whether notifications were sent for this comment for commenters. To prevent notifications being sent on imports, set this to true. **/
72 notificationSentForParent?: boolean
73 /** Whether notifications were sent for this comment for tenant users. To prevent notifications being sent on imports, set this to true. **/
74 notificationSentForParentTenant?: boolean
75 /** The title of the page this comment was on. **/
76 pageTitle?: string
77 /** If we're replying to a comment, this is the ID that we are replying to. **/
78 parentId?: string|null
79 /** Whether the comment is marked reviewed. **/
80 reviewed: boolean
81 /** The tenant id where the comment belongs. **/
82 tenantId: string
83 /** The user that wrote the comment. Created automatically when saving a comment with a name/email. **/
84 userId?: string|null
85 /** The URL to the location that this comment is visible, like a blog post. **/
86 url: string
87 /** A "cleaned" version of the urlId you passed us. When saving, you specify this field, but when you fetch the comment back this will be "cleaned" and your original value moved to "urlIdRaw". **/
88 urlId: string
89 /** READONLY: The original urlId you passed us. **/
90 urlIdRaw?: string
91 /** Is the user and this comment verified? **/
92 verified: boolean
93 /** Number of votes up. **/
94 votesUp?: number
95 /** Number of votes down. **/
96 votesDown?: number
97 /** The "karma" of the comment (= votes up - votes down). **/
98 votes?: number
99}
100

Algunos de estos campos están marcados como READONLY - estos son devueltos por la API pero no pueden ser establecidos.

Estructura del Texto del Comentario

Los comentarios se escriben en un sabor de markdown de FastComments, que es simplemente markdown más etiquetas tradicionales estilo bbcode para imágenes, como [img]ruta[/img].

El texto se almacena en dos campos. El texto que el usuario ingresó se almacena sin modificar en el campo comment. Esto se renderiza y almacena en el campo commentHTML.

Las etiquetas HTML permitidas son b, u, i, strike, pre, span, code, img, a, strong, ul, ol, li, y br.

Se recomienda renderizar el HTML, ya que es un subconjunto muy pequeño de HTML, construir un renderizador es bastante sencillo. Hay múltiples bibliotecas para React Native y Flutter, por ejemplo, para ayudar con esto.

Puede elegir renderizar el valor no normalizado del campo comment. Un ejemplo de analizador está aquí..

El ejemplo de analizador también podría ajustarse para trabajar con HTML, y transformar las etiquetas HTML en elementos esperados para renderizar para su plataforma.

Etiquetado

Cuando los usuarios son etiquetados en un comentario, la información se almacena en una lista llamada mentions. Cada objeto en esa lista tiene la siguiente estructura.

El Objeto de Menciones de Comentario
Copy CopyRun External Link
1
2interface CommentUserMention {
3 /** The user id. For SSO users, this will have your tenant id prefixed. **/
4 id: string
5 /** The final @mention tag text, including the @ symbol. **/
6 tag: string
7 /** The original @mention tag text, including the @ symbol. **/
8 rawTag: string
9 /** What type of user was tagged. user = FastComments.com account. sso = SSOUser. **/
10 type: 'user'|'sso'
11 /** If the user opts out of notifications, this will still be set to true. **/
12 sent: boolean
13}
14

HashTags

Cuando se usan hashtags y se analizan con éxito, la información se almacena en una lista llamada hashTags. Cada objeto en esa lista tiene la siguiente estructura. Los hashtags también pueden agregarse manualmente al array hashTags del comentario para consultas, si se establece retain.

El Objeto HashTag de Comentario
Copy CopyRun External Link
1
2interface CommentHashTag {
3 /** The hashtag id. **/
4 id: string
5 /** The final #hashtag tag text, including the # symbol. **/
6 tag: string
7 /** If the hashtag is associated with a custom URL, this will be defined. **/
8 url?: string
9 /** If we should retain the hashtag, even if it does not exist in the comment text, when the comment is updated. Useful for tagging comments without changing comment text. **/
10 retain?: boolean
11}
12

Estructura de plantilla de correo electrónico Internal Link

Un objeto EmailTemplate representa la configuración para una plantilla de email personalizada, para un inquilino.

El sistema seleccionará la plantilla de email a usar mediante:

  • Su identificador de tipo, lo llamamos emailTemplateId. Estos son constantes.
  • El domain. Primero intentaremos encontrar una plantilla para el dominio al que está vinculado el objeto relacionado (como un Comment), y si no se encuentra una coincidencia entonces intentaremos encontrar una plantilla donde domain sea null o *.

La estructura del objeto EmailTemplate es la siguiente:

Estructura de Plantilla de Email
Copy Copy
1
2interface EmailTemplate {
3 id: string
4 tenantId: string
5 emailTemplateId: string
6 displayName: string
7 /** READONLY **/
8 createdAt: string
9 /** READONLY **/
10 updatedAt: string
11 /** READONLY **/
12 updatedByUserId: string
13 /** The domain the template should be associated with. **/
14 domain?: string | '*' | null
15 /** The email template content in EJS syntax. **/
16 ejs: string
17 /** A map of overridden translation keys to values, for each supported locale. **/
18 translationOverridesByLocale: Record<string, Record<string, string>>
19 /** An object that represents the render context of the template. **/
20 testData: object
21}
22

Notas

  • Puede obtener los valores válidos de emailTemplateId desde el endpoint /definitions.
  • El endpoint /definitions también incluye las traducciones predeterminadas y datos de prueba.
  • Las plantillas fallarán al guardar con estructura o datos de prueba inválidos.

Estructura de hashtag Internal Link

Un objeto HashTag representa una etiqueta que puede ser dejada por un usuario. Los HashTags pueden usarse para vincular a una pieza externa de contenido o para vincular comentarios relacionados juntos.

La estructura del objeto HashTag es la siguiente:

Estructura de HashTag
Copy Copy
1
2interface HashTag {
3 /** Should start with the "#" or desired character. **/
4 tag: string
5 /** An optional URL that the hashtag can point to. Instead of filtering comments by hashtag, the UI will redirect to this upon click. **/
6 url?: string
7 /** READONLY **/
8 createdAt: string
9}
10

Notas:

  • En algunos endpoints de API verá que el hashtag se usa en la URL. Recuerde usar valores codificados en URI. Por ejemplo, # debe representarse como %23.
  • Algunos de estos campos están marcados como READONLY - estos son devueltos por la API pero no pueden ser establecidos.

Estructura de conteo de notificaciones Internal Link

Un objeto NotificationCount representa el conteo de notificaciones no leídas y metadatos para un usuario.

Si no hay notificaciones no leídas, no habrá un NotificationCount para el usuario.

Los objetos NotificationCount se crean automáticamente y no pueden crearse vía la API. También expiran después de un año.

Puede limpiar el conteo de notificaciones no leídas de un usuario eliminando su NotificationCount.

La estructura del objeto NotificationCount es la siguiente:

Estructura de NotificationCount
Copy Copy
1
2interface NotificationCount {
3 id: string // user id
4 count: number
5 createdAt: string // date string
6 expireAt: string // date string
7}
8

Estructura de notificación Internal Link

Un objeto Notification representa una notificación para un usuario.

Los objetos Notification se crean automáticamente y no pueden crearse vía la API. También expiran después de un año. Las notificaciones no pueden eliminarse. Sin embargo, pueden actualizarse para establecer viewed a false, y puede consultar por viewed.

Un usuario también puede optar por no recibir notificaciones para un comentario específico estableciendo optedOut en la notificación a true. Puede optar por participar nuevamente estableciéndolo a false.

Hay diferentes tipos de notificaciones - consulte relatedObjectType y type.

Las formas en que se crean las notificaciones es bastante flexible y puede ser activada por muchos escenarios (ver NotificationType).

A día de hoy, la existencia de una Notification no implica realmente que un email se envíe o deba enviarse. Más bien, las notificaciones se usan para el feed de notificaciones e integraciones relacionadas.

La estructura del objeto Notification es la siguiente:

Estructura de Notification
Copy Copy
1
2enum NotificationObjectType {
3 Comment = 0,
4 Profile = 1,
5 Tenant = 2
6}
7
8enum NotificationType {
9 /** If someone replied to you. **/
10 RepliedToMe = 0,
11 /** If someone replied anywhere in a thread (even children of children) of a thread you commented on. **/
12 RepliedTransientChild = 1,
13 /** If your comment was up-voted. **/
14 VotedMyComment = 2,
15 /** If a new comment is left on the root of a page you're subscribed to. **/
16 SubscriptionReplyRoot = 3,
17 /** If someone commented on your profile. **/
18 CommentedOnProfile = 4,
19 /** If you have a DM. **/
20 DirectMessage = 5,
21 /** TrialLimits is for tenant users only. **/
22 TrialLimits = 6,
23 /** If you were @mentioned. **/
24 Mentioned = 7
25}
26
27interface Notification {
28 id: string
29 tenantId: string
30 /** With SSO, the user id is in the format `<tenant id>:<user id>`. **/
31 userId?: string
32 /** When working with SSO, you only have to worry about `userId`. **/
33 anonUserId?: string
34 /** urlId is almost always defined. It is only optional for tenant-level notifications, which are infrequent. **/
35 urlId?: string
36 /** URL is cached for quick navigation to the source of the notification. **/
37 url?: string
38 /** Page Title is cached for quick reading of notification source. **/
39 pageTitle?: string
40 relatedObjectType: NotificationObjectType
41 /** For example, comment id. **/
42 relatedObjectId: string
43 viewed: boolean
44 createdAt: string // date string
45 type: NotificationType
46 fromCommentId?: string
47 fromVoteId?: string
48 /** fromUserName and fromUserAvatarSrc are cached here for quick displaying of the notification. They are updated when the user is updated. **/
49 fromUserName: string
50 fromUserId: string
51 fromUserAvatarSrc?: string
52 /** Set this to true to stop getting notifications for this object. **/
53 optedOut?: boolean
54}
55

Estructura de página Internal Link

Un objeto Page representa la página a la que pueden pertenecer muchos comentarios. Esta relación se define por urlId.

Una Page almacena información como el título de la página, el conteo de comentarios, y urlId.

La estructura del objeto Page es la siguiente:

Estructura de Page
Copy Copy
1
2interface Page {
3 id: string
4 urlId: string
5 url: string
6 title?: string
7 createdAt: string
8 commentCount: number
9 rootCommentCount: number
10 /** Setting this to null means all SSO users can see the page. An empty list means it is closed to all users. **/
11 accessibleByGroupIds?: string[] | null
12 /** Is this page closed for new comments? **/
13 isClosed?: boolean
14}
15

Estructura de evento webhook pendiente Internal Link

Un objeto PendingWebhookEvent representa un evento de webhook en cola que está pendiente.

Los objetos PendingWebhookEvent se crean automáticamente y no pueden crearse manualmente vía la API. También expiran después de un año. Pueden eliminarse lo que remueve la tarea de la cola.

Hay diferentes tipos de eventos - consulte eventType (OutboundSyncEventType) y type (OutboundSyncType).

Un caso de uso común para esta API es implementar monitoreo personalizado. Puede querer llamar al endpoint /count periódicamente para sondear el conteo pendiente para filtros dados.

La estructura del objeto PendingWebhookEvent es la siguiente:

Estructura de PendingWebhookEvent
Copy Copy
1
2enum OutboundSyncEventType {
3 Create: 0,
4 Delete: 1,
5 Update: 2
6}
7
8enum OutboundSyncType {
9 /** WordPress-specific sync task. **/
10 WP: 0,
11 Webhook: 1
12}
13
14interface PendingWebhookEvent {
15 id: string
16 /** The comment id associated with the event. **/
17 commentId: string
18 /** The comment object for the event at the time of the event. We started adding these in Nov 2023. **/
19 comment: Comment
20 /** An external id that may be associated with the comment. **/
21 externalId: string | null
22 createdAt: Date
23 tenantId: string
24 attemptCount: number
25 /** Set before first attempt, and after every failure. **/
26 nextAttemptAt: Date
27 /** Whether this is a creation, deletion, or update event... **/
28 eventType: OutboundSyncEventType
29 /** The type of sync to perform (WordPress, call API, etc). **/
30 type: OutboundSyncType
31 /** The domain that matched the comment. We use this domain to pick the API key. **/
32 domain: string
33 /** The last error that occurred. This type is untyped and is a "dump" of whatever happened. Usually it contains an object with statusCode, body, and a headers map. **/
34 lastError: object | null
35}
36

Estructura de usuario SSO Internal Link

FastComments proporciona una solución SSO fácil de usar. Actualizar la información de un usuario con la integración basada en HMAC es tan simple como hacer que el usuario cargue la página con un payload actualizado.

Sin embargo, puede ser deseable gestionar un usuario fuera de ese flujo, para mejorar la consistencia de su aplicación.

La API de Usuario SSO proporciona una forma de hacer CRUD en objetos que llamamos SSOUsers. Estos objetos son diferentes de los Usuarios regulares y se mantienen separados por seguridad de tipos.

La estructura del objeto SSOUser es la siguiente:

Estructura de SSOUser
Copy Copy
1
2interface SSOUser {
3 id: string
4 username: string
5 email?: string
6 websiteUrl?: string
7 signUpDate: number
8 createdFromUrlId?: string
9 loginCount?: number
10 avatarSrc?: string
11 optedInNotifications?: boolean
12 optedInSubscriptionNotifications?: boolean
13 displayLabel?: string
14 displayName?: string
15 isAccountOwner?: boolean // Admin permission - SSO users with this flag are billed as SSO Admins (separate from regular SSO users)
16 isAdminAdmin?: boolean // Admin permission - SSO users with this flag are billed as SSO Admins (separate from regular SSO users)
17 isCommentModeratorAdmin?: boolean // Moderator permission - SSO users with this flag are billed as SSO Moderators (separate from regular SSO users)
18 /** If null, Access Control will not be applied to the user. If an empty list, this user will not be able to see any pages or @mention other users. **/
19 groupIds?: string[] | null
20 createdFromSimpleSSO?: boolean
21 /** Don't let other users see this user's activity, including comments, on their profile. Default is true to provide secure profiles by default. **/
22 isProfileActivityPrivate?: boolean
23 /** Don't let other users leave comments on the user's profile, or see existing profile comments. Default false. **/
24 isProfileCommentsPrivate?: boolean
25 /** Don't let other users send direct messages to this user. Default false. **/
26 isProfileDMDisabled?: boolean
27 karma?: number
28 /** Optional configuration for user badges. **/
29 badgeConfig?: {
30 /** Array of badge IDs to assign to the user. Limited to 30 badges. Order is respected. **/
31 badgeIds: string[]
32 /** If true, replaces all existing displayed badges with the provided ones. If false, adds to existing badges. **/
33 override?: boolean
34 /** If true, updates badge display properties from tenant configuration. **/
35 update?: boolean
36 }
37}
38

Facturación para Usuarios SSO

Los usuarios SSO se facturan de manera diferente según sus banderas de permisos:

  • Usuarios SSO Regulares: Los usuarios sin permisos de administrador o moderador se facturan como usuarios SSO regulares
  • Administradores SSO: Los usuarios con banderas isAccountOwner o isAdminAdmin se facturan por separado como Administradores SSO (misma tarifa que los administradores de inquilino regulares)
  • Moderadores SSO: Los usuarios con bandera isCommentModeratorAdmin se facturan por separado como Moderadores SSO (misma tarifa que los moderadores regulares)

Importante: Para prevenir doble facturación, el sistema automáticamente deduplica usuarios SSO contra usuarios de inquilino regulares y moderadores por dirección de email. Si un usuario SSO tiene el mismo email que un usuario de inquilino regular o moderador, no serán facturados dos veces.

Control de Acceso

Los usuarios pueden dividirse en grupos. Esto es para lo que es el campo groupIds, y es opcional.

@Menciones

Por defecto @mentions usará username para buscar otros usuarios sso cuando se escribe el carácter @. Si se usa displayName, entonces los resultados que coincidan con username serán ignorados cuando haya una coincidencia para displayName, y los resultados de búsqueda de @mention usarán displayName.

Suscripciones

Con FastComments, los usuarios pueden suscribirse a una página haciendo clic en el icono de campana en el widget de comentarios y haciendo clic en Suscribirse.

Con un usuario regular, les enviamos emails de notificación basados en sus configuraciones de notificación.

Con Usuarios SSO, dividimos esto para compatibilidad hacia atrás. Los usuarios solo recibirán estos emails de notificación de suscripción adicionales si establece optedInSubscriptionNotifications a true.

Insignias

Puede asignar insignias a usuarios SSO usando la propiedad badgeConfig. Las insignias son indicadores visuales que aparecen junto al nombre de un usuario en los comentarios.

  • badgeIds - Un array de IDs de insignias para asignar al usuario. Estos deben ser IDs de insignias válidos creados en su cuenta de FastComments. Limitado a 30 insignias.
  • override - Si es verdadero, todas las insignias existentes mostradas en comentarios serán reemplazadas con las proporcionadas. Si es falso u omitido, las insignias proporcionadas se agregarán a cualquier insignia existente.
  • update - Si es verdadero, las propiedades de visualización de insignias se actualizarán desde la configuración del inquilino cada vez que el usuario inicie sesión.

Estructura de suscripción Internal Link

Un objeto Subscription representa una suscripción para un usuario.

Los objetos Subscription se crean cuando un usuario hace clic en la campana de notificación en el widget de comentarios y hace clic en "Suscribirse a esta página".

Las suscripciones también pueden crearse vía la API.

Tener un objeto Subscription causa que se generen objetos Notification, y se envíen emails, cuando se dejan nuevos comentarios en la raíz de la página asociada para la cual es la Subscription. El envío de emails depende del tipo de usuario. Para usuarios regulares esto depende de optedInNotifications. Para Usuarios SSO esto depende de optedInSubscriptionNotifications. Tenga en cuenta que algunas aplicaciones pueden no tener el concepto de una página accesible por web, en cuyo caso simplemente establezca urlId al id del elemento al que se está suscribiendo (mismo valor para urlId que pasaría al widget de comentarios).

La estructura del objeto Subscription es la siguiente:

Estructura de Subscription
Copy Copy
1
2interface Subscription {
3 id: string
4 tenantId: string
5 /** With SSO, the user id is in the format `<tenant id>:<user id>`. **/
6 userId: string
7 anonUserId?: string
8 urlId: string
9 url?: string
10 pageTitle?: string
11 createdAt: string // date string
12}
13

Estructura de uso diario del tenant Internal Link

Un objeto TenantDailyUsage representa el uso para un inquilino en un día dado. Si no hubo actividad para un inquilino dado en un día dado, ese día no tendrá un objeto TenantDailyUsage.

El objeto TenantDailyUsage no es en tiempo real y puede estar minutos detrás del uso real.

La estructura del objeto TenantDailyUsage es la siguiente:

Estructura de TenantDailyUsage
Copy Copy
1
2export interface TenantDailyUsage {
3 yearNumber: number
4 monthNumber: number
5 dayNumber: number
6 commentFetchCount?: number
7 commentCreateCount?: number
8 conversationCreateCount?: number
9 voteCount?: number
10 accountCreatedCount?: number
11 userMentionSearch?: number
12 hashTagSearch?: number
13 gifSearchTrending?: number
14 gifSearch?: number
15 apiCreditsUsed?: number
16 createdAt: string
17 billed: boolean
18 /** Ignored for billing. **/
19 ignored: boolean
20}
21

Estructura de tenant Internal Link

El Tenant define un cliente de FastComments.com. Pueden ser creados a través de la API por inquilinos con acceso de marca blanca. Los inquilinos de marca blanca no pueden crear otros inquilinos de marca blanca (solo se permite un nivel de anidación).

La estructura del objeto Tenant es la siguiente:

Estructura de Tenant
Copy Copy
1
2export enum SiteType {
3 Unknown = 0,
4 WordPress = 1
5}
6
7/** This can also be handled via the DomainConfig API. **/
8export interface TenantDomainConfig {
9 domain: string
10 emailFromName?: string
11 emailFromEmail?: string
12 createdAt?: string,
13 siteType?: FastCommentsSiteType, // you probably want Unknown
14 logoSrc?: string, // raw image path
15 logoSrc100px?: string, // resized for thumbnails
16 footerUnsubscribeURL?: string,
17 emailHeaders?: Record<string, string>,
18 disableUnsubscribeLinks?: boolean,
19 dkim?: {
20 domainName: string,
21 keySelector: string,
22 privateKey: string
23 }
24}
25
26export interface TenantBillingInfo {
27 name: string
28 address: string
29 city: string
30 state: string
31 zip: string
32 country: string
33}
34
35export enum TenantPaymentFrequency {
36 Monthly = 0,
37 Annually = 1
38}
39
40export interface Tenant {
41 id: string
42 name: string
43 email?: string
44 signUpDate: number; // number due to "legacy" reasons
45 packageId?: string | null
46 paymentFrequency?: TenantPaymentFrequency
47 billingInfoValid?: boolean
48 billingHandledExternally?: boolean
49 createdBy?: string
50 isSetup?: boolean
51 domainConfiguration: FastCommentsAPITenantDomainConfig[]
52 billingInfo?: FastCommentsAPITenantBillingInfo
53 stripeCustomerId?: string
54 stripeSubscriptionId?: string
55 stripePlanId?: string
56 enableProfanityFilter?: boolean
57 enableSpamFilter?: boolean
58 lastBillingIssueReminderDate?: string
59 removeUnverifiedComments?: boolean
60 unverifiedCommentsTTLms?: number
61 commentsRequireApproval?: boolean
62 autoApproveCommentOnVerification?: boolean
63 sendProfaneToSpam?: boolean
64 /** @readonly - Is calculated based on packageId. **/
65 hasFlexPricing?: boolean
66 /** @readonly **/
67 flexLastBilledAmount?: number
68 /** @readonly - Is calculated based on packageId. **/
69 hasAuditing?: boolean
70 /** You can store a key value pair with the tenant which you can use to query. Keys cannot contain "." or "$", or be longer than 100 chars. Values may not be longer than 2k chars. **/
71 meta?: Record<string, string | null>
72}
73

Estructura de usuario Internal Link

User es un objeto que representa el denominador más común de todos los usuarios.

Tenga en cuenta que en FastComments tenemos varios casos de uso diferentes para usuarios:

  • SSO Seguro
  • SSO Simple
  • Usuarios de Inquilino (Por ejemplo: Administradores)
  • Comentaristas

Esta API es para Comentaristas y usuarios creados a través de SSO Simple. Básicamente, cualquier usuario creado a través de su sitio puede ser accedido a través de esta API. Los Usuarios de Inquilino también pueden ser obtenidos de esta manera, pero obtendrá más información interactuando con la API /tenant-users/.

Para SSO Seguro por favor use la API /sso-users/.

No puede actualizar estos tipos de usuarios. Ellos crearon su cuenta a través de su sitio, por lo que proporcionamos acceso básico de solo lectura, pero no puede realizar cambios. Si desea tener este tipo de flujo - necesita configurar SSO Seguro.

La estructura del objeto User es la siguiente:

Estructura de User
Copy Copy
1
2export interface User {
3 /** This is also the id used as userId on comment objects. **/
4 id: string
5 username: string
6 /** A link to the commenter's blog, for example. **/
7 websiteUrl?: string
8 email: string
9 signUpDate: number
10 createdFromUrlId: string
11 createdFromTenantId: string
12 avatarSrc?: string
13 locale: FastCommentsLocale
14 displayLabel?: string
15 karma?: number
16}
17

Estructura de voto Internal Link

Un objeto Vote representa un voto dejado por un usuario.

La relación entre comentarios y votos se define mediante commentId.

La estructura del objeto Vote es la siguiente:

Estructura de Vote
Copy Copy
1
2interface Vote {
3 id: string
4 urlId: string
5 commentId: string
6 userId: string
7 direction: 1 | -1
8 createdAt: string
9}
10

Estructura de configuración de pregunta Internal Link

FastComments proporciona una forma de construir preguntas y agregar sus resultados. Un ejemplo de una pregunta (en adelante llamada QuestionConfig) podría ser una calificación de estrellas, un deslizador, o una pregunta NPS (determinado vía type).

Los datos de preguntas pueden agregarse individualmente, juntos, a lo largo del tiempo, en general, por página, y así sucesivamente.

El framework tiene todas las capacidades necesarias para construir widgets del lado del cliente (con su servidor frente a esta API), dashboards de administración, y herramientas de informes.

Primero, tenemos que definir un QuestionConfig. La estructura es la siguiente:

Estructura de QuestionConfig
Copy Copy
1
2type QuestionConfigType = 'nps' | 'slider' | 'star' | 'thumbs';
3
4interface QuestionConfig {
5 id: string
6 tenantId: string
7 name: string
8 question: string
9 helpText?: string
10 createdAt: string
11 createdBy: string
12 /** READONLY - incremented for each new response. **/
13 usedCount: number
14 /** A date string for when the configuration was last used (result left). **/
15 lastUsed?: string
16 type: QuestionConfigType
17 numStars?: number
18 min?: number
19 max?: number
20 defaultValue?: number
21 labelNegative?: string
22 labelPositive?: string
23 subQuestionIds?: string[]
24 alwaysShowSubQuestions?: boolean
25 reportingOrder: number
26}
27

Estructura de resultado de pregunta Internal Link

Para guardar resultados de preguntas, crea un QuestionResult. Luego puede agregar resultados de preguntas, y también vincularlos a comentarios para propósitos de informes.

Estructura de QuestionResult
Copy Copy
1
2interface QuestionResultMeta {
3 name: string
4 values: string[]
5}
6
7interface QuestionResult {
8 id: string
9 tenantId: string
10 urlId: string
11 anonUserId?: string
12 userId?: string
13 createdAt?: string
14 value: number
15 commentId?: string
16 questionId: string
17 meta?: QuestionResultMeta[]
18}
19

Estructura de insignia de usuario Internal Link

UserBadge es un objeto que representa una insignia asignada a un usuario en el sistema FastComments.

Las insignias pueden ser asignadas a usuarios automáticamente basándose en su actividad (como cantidad de comentarios, tiempo de respuesta, estado de veterano) o manualmente por los administradores del sitio.

La estructura del objeto UserBadge es la siguiente:

Estructura de UserBadge
Copy Copy
1
2export interface UserBadge {
3 /** Unique identifier for this user badge assignment */
4 id: string
5 /** ID of the user this badge is assigned to */
6 userId: string
7 /** ID of the badge definition from the tenant's badge catalog */
8 badgeId: string
9 /** ID of the tenant that created/assigned this badge */
10 fromTenantId: string
11 /** When this badge was created (milliseconds since epoch) */
12 createdAt?: number
13 /** When this badge was received by the user (milliseconds since epoch) */
14 receivedAt?: number
15 /**
16 * The badge type:
17 * 0=CommentCount, 1=CommentUpVotes, 2=CommentReplies, 3=CommentsPinned,
18 * 4=Veteran, 5=NightOwl, 6=FastReplyTime, 7=ModeratorCommentsDeleted,
19 * 8=ModeratorCommentsApproved, 9=ModeratorCommentsUnapproved, 10=ModeratorCommentsReviewed,
20 * 11=ModeratorCommentsMarkedSpam, 12=ModeratorCommentsMarkedNotSpam, 13=RepliedToSpecificPage,
21 * 14=Manual
22 */
23 type: number
24 /** For threshold-based badges, the threshold value */
25 threshold?: number
26 /** The name/label of the badge */
27 name?: string
28 /** Detailed description of the badge */
29 description?: string
30 /** The text shown on the badge */
31 displayLabel?: string
32 /** URL to an image shown on the badge */
33 displaySrc?: string
34 /** Background color for the badge (hex code) */
35 backgroundColor?: string
36 /** Border color for the badge (hex code) */
37 borderColor?: string
38 /** Text color for the badge (hex code) */
39 textColor?: string
40 /** Additional CSS class for styling */
41 cssClass?: string
42 /** For veteran badges, the time threshold in milliseconds */
43 veteranUserThresholdMillis?: number
44 /** Whether this badge is displayed on the user's comments */
45 displayedOnComments: boolean
46 /** The display order of the badge */
47 order?: number
48}
49

Estructura de progreso de insignia de usuario Internal Link

UserBadgeProgress es un objeto que representa el progreso de un usuario hacia la obtención de varias insignias en el sistema FastComments.

Este seguimiento ayuda a determinar cuándo los usuarios deben recibir insignias automáticas basadas en su actividad y participación en su comunidad.

La estructura del objeto UserBadgeProgress es la siguiente:

Estructura de UserBadgeProgress
Copy Copy
1
2export interface UserBadgeProgress {
3 /** Unique identifier for this progress record */
4 id: string
5 /** ID of the tenant this progress record belongs to */
6 tenantId: string
7 /** ID of the user this progress record tracks */
8 userId: string
9 /** ID of the user's first comment in the system */
10 firstCommentId?: string
11 /** Date of the user's first comment (milliseconds since epoch) */
12 firstCommentDate?: number
13 /** Automatically calculated trust factor based on user activity */
14 autoTrustFactor?: number
15 /** Manually set trust factor by administrators */
16 manualTrustFactor?: number
17 /** Detailed progress object with various metrics, keys match BadgeType enum */
18 progress: {
19 /** 0: CommentCount - Count of comments the user has made */
20 '0'?: number
21 /** 1: CommentUpVotes - Count of upvotes the user has received */
22 '1'?: number
23 /** 2: CommentReplies - Count of replies the user has made */
24 '2'?: number
25 /** 3: CommentsPinned - Count of pinned comments the user has */
26 '3'?: number
27 /** 4: Veteran - User's account age */
28 '4'?: number
29 /** 5: NightOwl - Times user has posted during nighttime hours */
30 '5'?: number
31 /** 6: FastReplyTime - Average reply time in milliseconds */
32 '6'?: number
33 /** 7: ModeratorCommentsDeleted - For moderator badges, comments deleted count */
34 '7'?: number
35 /** 8: ModeratorCommentsApproved - For moderator badges, comments approved count */
36 '8'?: number
37 /** 9: ModeratorCommentsUnapproved - For moderator badges, comments unapproved count */
38 '9'?: number
39 /** 10: ModeratorCommentsReviewed - For moderator badges, comments reviewed count */
40 '10'?: number
41 /** 11: ModeratorCommentsMarkedSpam - For moderator badges, comments marked as spam count */
42 '11'?: number
43 /** 12: ModeratorCommentsMarkedNotSpam - For moderator badges, comments marked as not spam count */
44 '12'?: number
45 /** 13: RepliedToSpecificPage - For each page, count of replies */
46 '13'?: Record<string, number>
47 }
48}
49

En conclusión

Esperamos que haya encontrado nuestra documentación de la API detallada y fácil de entender. Si encuentra alguna laguna, háganoslo saber abajo.