diff --git a/sdks/javascript/README.md b/sdks/javascript/README.md index afaa44b..8c37fda 100644 --- a/sdks/javascript/README.md +++ b/sdks/javascript/README.md @@ -1,8 +1,32 @@ # @socialhose/api -TypeScript SDK for the Socialhose Public API. +Official TypeScript SDK for the Socialhose Public API. -Use it from backend TypeScript/JavaScript to fetch campaigns, analytics, mentions, mailing lists, and SDK-composed entity analytics with authentication, retries, timeouts, and caching handled consistently. +Socialhose is a social-listening and media-monitoring API for turning large streams of public mentions into usable campaign intelligence. It helps backend applications answer questions like: + +- What are people saying about a campaign, brand, organization, product, policy, person, or event? +- Which platforms are driving the conversation? +- Is sentiment improving or deteriorating? +- Which mentions have the most reach or engagement? +- Which keywords, topics, or entities are trending? +- Who should receive alerts or mailing-list updates? + +The SDK wraps the Socialhose REST API with typed JavaScript/TypeScript methods for campaign discovery, analytics dashboards, mention search, mailing lists, and SDK-composed entity analytics. It handles API-key auth, browser-compatible headers, retries, timeouts, GET caching, and normalized response shapes so product code can focus on the analysis instead of raw HTTP plumbing. + +## What you can build with it + +Use `@socialhose/api` from server-side JavaScript/TypeScript to build: + +- Social-listening dashboards for campaigns, topics, brands, people, organizations, or locations. +- Monitoring tools that search public mentions across supported platforms. +- Analytics views showing volume, reach, engagement, sentiment, platform mix, and growth. +- Trend and keyword reports. +- High-impact mention feeds ordered by recency or engagement. +- Entity pages that summarize one term/person/company/topic using mention-search facets. +- Alerting and mailing-list workflows backed by Socialhose mailing lists. +- Batch jobs, CLI scripts, or serverless functions that pull Socialhose data into another system. + +This package is intended for **backend code only**. Do not ship your Socialhose API key to browsers. ## Install @@ -30,13 +54,134 @@ const mentions = await socialhose.getMentions({ console.log(mentions.count, mentions.results[0]?.content); ``` -## Documentation +## Core capabilities -- [Usage guide](./docs/GUIDE.md) — what the SDK is, setup, common workflows, operational guidance. -- [API reference](./docs/API.md) — every public class, function, method, option, and exported type. -- [Entity analytics](./docs/ENTITY_ANALYTICS.md) — how term-level analytics are built, accuracy safeguards, rate-limit guidance. -- [Caching and retries](./docs/CACHING_AND_RETRIES.md) — cache contract, retry policy, failure semantics. -- [Examples](./examples) — runnable TypeScript examples. +### Campaign discovery + +Campaigns are the API's top-level monitoring containers. Use them to discover what this API key can access, resolve IDs, and scope analytics or mention search. + +```ts +const campaigns = await socialhose.getCampaigns(); +const campaign = await socialhose.getCampaign(campaigns[0].id); +``` + +Related methods: + +- `getCampaigns()` — fetches the first page of accessible campaigns. +- `getCampaign(id)` — fetches one campaign by ID. +- `getCampaignIdByMatch(match)` — convenience helper that finds a campaign ID by case-insensitive name substring. + +### Analytics dashboards + +Analytics methods summarize campaign performance and conversation health. + +```ts +const filters = { + campaign_ids: 'campaign-id', + date_from: '2026-05-01', + date_to: '2026-05-29', +}; + +const [overview, timeline, sentiment, platforms] = await Promise.all([ + socialhose.getOverview(filters), + socialhose.getTimeline({ ...filters, interval: 'day' }), + socialhose.getSentiment(filters), + socialhose.getPlatforms(filters), +]); +``` + +Analytics methods include: + +- `getOverview()` — total mentions, authors, estimated reach, sentiment distribution, platform breakdown, engagement, and growth. +- `getTimeline()` — time-series mention volume with sentiment and engagement buckets. +- `getSentiment()` — aggregate and platform-specific sentiment splits. +- `getShareOfVoice()` — compares campaigns by mention share, engagement, and sentiment. +- `getPlatforms()` — mention and engagement totals grouped by platform. +- `getTopKeywords()` — most frequent keywords with sentiment split. +- `getTrending()` — keywords whose volume changed against the previous period. +- `getTopMentions()` — high-impact mentions with reach, engagement, author, URL, and content preview. + +### Mention search + +Mentions are the underlying public posts/articles/items Socialhose has collected and classified. Search them by campaign, date, platform, sentiment, content, page, and ordering. + +```ts +const page = await socialhose.getMentions({ + campaign_ids: 'campaign-id', + content_search: 'ozempic', + platforms: 'twitter,reddit', + sentiments: 'negative', + ordering: '-engagement_count', +}); + +console.log(page.count); +for (const mention of page.results) { + console.log(mention.platform, mention.sentiment, mention.url); +} +``` + +Use this for feeds, search results, moderation queues, source inspection, custom reports, or downstream enrichment. + +### Entity analytics + +Entity helpers build analytics around one search term even when native analytics endpoints are campaign-scoped. They use `/mentions/` facets to produce compact profiles for people, organizations, brands, products, places, hashtags, or arbitrary terms. + +```ts +const stats = await socialhose.getEntityStats('RSF', 'campaign-id', { + revalidateSeconds: 900, +}); + +console.log({ + total: stats.total, + sentiment: stats.sentiment, + platformMix: stats.platformMix, + momentumPct: stats.momentumPct, + topUrls: stats.sample.slice(0, 3).map((m) => m.url), +}); +``` + +Entity methods: + +- `getEntityBrief(term, campaignId?)` — one request for count plus a top-engagement sample; derives sentiment and platform mix from the sample. +- `getEntityStats(term, campaignId?)` — richer entity profile with exact facet reconciliation, newest mentions, daily sparkline, and momentum. +- `getEntityBriefs(terms, campaignId?, concurrency?)` — batch entity cards with bounded concurrency. + +Entity analytics can fan out many requests. Use caching and conservative concurrency for production dashboards. + +### Mailing lists + +Mailing-list helpers support Socialhose alert/recipient workflows. + +```ts +const lists = await socialhose.getMailingLists(); + +const result = await socialhose.inviteMailingListMember(lists[0].id, { + email: 'analyst@example.com', + first_name: 'Ada', + last_name: 'Lovelace', +}); +``` + +Methods: + +- `getMailingLists()` — fetches first-page mailing-list metadata. +- `inviteMailingListMember()` — invites a recipient and normalizes `201` and `409` outcomes into `invited` or `already`. + +### Low-level access + +If the SDK does not yet expose a typed helper for an endpoint, use authenticated low-level methods: + +```ts +const raw = await socialhose.get('/mentions/', { + page: 1, + content_search: 'cholera', +}); + +const created = await socialhose.post('/some-endpoint/', { value: true }); +``` + +- `get(path, params?, options?)` — authenticated cached GET with query serialization. +- `post(path, body, options?)` — authenticated JSON POST, never cached. ## Configuration @@ -50,28 +195,40 @@ const socialhose = new SocialhoseClient({ }); ``` +Important options: + +- `apiKey` — required Socialhose API key. Missing keys fail on the first request. +- `baseUrl` — defaults to `https://socialhose.net/api/public/v1`. +- `timeoutMs` — per-attempt timeout. Default: `8000`. +- `retries` — retry count for network failures, timeouts, `429`, and `5xx`. Default: `3`. +- `cacheTtlMs` — default GET cache TTL in milliseconds. Default: `60000`; set `0` to disable built-in memory caching. +- `cache` — custom cache implementation, e.g. Redis or a platform cache. +- `fetch` — custom fetch for tests, instrumentation, or non-standard runtimes. +- `defaultHeaders` — extra headers sent with every request. + The SDK sends `Authorization: Api-Key ` and a browser-like `User-Agent` by default. The user-agent is intentional: the current Socialhose API edge rejects some non-browser requests. -## Main capabilities +## Caching, retries, and failure behavior -- Campaign discovery: `getCampaigns()`, `getCampaign(id)`, `getCampaignIdByMatch(match)`. -- Analytics: `getOverview()`, `getTimeline()`, `getSentiment()`, `getShareOfVoice()`, `getPlatforms()`, `getTopKeywords()`, `getTrending()`, `getTopMentions()`. -- Mentions: `getMentions()` with campaign, date, platform, sentiment, text search, pagination, and ordering filters. -- Mailing lists: `getMailingLists()`, `inviteMailingListMember()`. -- Entity analytics: `getEntityBrief()`, `getEntityStats()`, `getEntityBriefs()`. -- Low-level access: `get(path, params)`, `post(path, body)`. -- Caching: built-in `MemoryCache`, disabling via `NoopCache`, or any custom `Cache` implementation. - -## Entity analytics warning - -Entity analytics fan out multiple `/mentions/` requests per term. Use `cacheTtlMs`, `revalidateSeconds`, or a persistent shared cache to stay under the approximate 60 req/min API-key rate limit. +- GET requests are cached by full URL. +- POST requests are never cached. +- Default cache is process-local `MemoryCache`. +- `NoopCache` disables storage. +- Custom caches implement `Cache#get`, `Cache#set`, and `Cache#delete`. +- `revalidateSeconds` overrides TTL per request. +- Non-positive TTL means “do not cache”. +- Transient failures are retried: network errors, timeouts, `429`, and `5xx`. +- Client errors such as `400`, `401`, `403`, and `404` are not retried. ```ts -const stats = await socialhose.getEntityStats('RSF', 'campaign-id', { - revalidateSeconds: 900, -}); +await socialhose.getMentions( + { content_search: 'sudan' }, + { revalidateSeconds: 900 }, +); ``` +For multi-process, serverless, or high-traffic dashboards, inject a shared cache instead of relying on the default in-memory cache. + ## Errors Failed requests throw `SocialhoseError` with `status`, `path`, `body`, and `cause` when available. @@ -88,6 +245,14 @@ try { } ``` +## Documentation + +- [Usage guide](./docs/GUIDE.md) — setup, workflows, filtering, pagination, caching, and operational guidance. +- [API reference](./docs/API.md) — every public class, function, method, option, and exported type. +- [Entity analytics](./docs/ENTITY_ANALYTICS.md) — how term-level analytics are built, accuracy safeguards, and rate-limit guidance. +- [Caching and retries](./docs/CACHING_AND_RETRIES.md) — cache contract, retry policy, request lifecycle, and failure semantics. +- [Examples](./examples) — runnable TypeScript examples. + ## Development ```bash