@comher.de/watchtime-api
v1.0.0
Published
A TypeScript library to track children's watch time using a DynamoDB backend
Downloads
7
Maintainers
Readme
WatchTimeLib
A TypeScript library designed to track children's watch time using a DynamoDB-based backend service. This library offers functionality to publish events, manage watch activities, and retrieve watch activities while respecting daily boundaries and handling open-ended activities.
Features
- Retrieve the version of the backend API.
- Publish events with optional timestamps.
- Publish watch activities with a start time and duration (creates start and end events).
- Retrieve watch activities within a specified time range, with support for daily boundaries and open-ended activities.
- Configure the service URL via environment variables.
- Customize the "day break" hour to define when a new "activity day" begins (e.g., reset at 2 AM).
Installation
To install the watchtime-lib library, run the following command in your terminal:
npm install watchtime-libThis will add the library to your project's dependencies.
Setup
Before using the library, complete the following setup steps:
1. Environment Variable Configuration
The library relies on an environment variable WATCHTIME_API_URL to connect to the backend service. Follow these steps:
Set the Environment Variable:
- Define
WATCHTIME_API_URLin your environment (e.g., via a.envfile or your build system's configuration). - Example:
WATCHTIME_API_URL=https://your-backend-url. - If not set, the library defaults to
http://localhost:3000.
- Define
Framework-Specific Notes:
- Create React App: Use
REACT_APP_WATCHTIME_API_URL(e.g., addREACT_APP_WATCHTIME_API_URL=https://your-backend-urlto your.envfile). - Vite or Webpack: Use
WATCHTIME_API_URLdirectly in your.envfile and ensure your build tool injects it.
- Create React App: Use
2. Build-Time Configuration
Ensure your build tool properly injects environment variables:
- For Create React App, variables must be prefixed with
REACT_APP_. - For Vite, add the
.envfile at the root and useimport.meta.env.WATCHTIME_API_URL. - For Webpack, configure the
DefinePluginor use a similar method to expose the variable.
Verify the variable is available in your application before initializing the library.
Usage
Below are detailed examples of how to use the library's core features.
1. Initialize the Library
Import and initialize the WatchTimeTracker class. You can provide the API URL explicitly or rely on the environment variable.
import { WatchTimeTracker } from "watchtime-lib";
// Initialize with the API URL (falls back to http://localhost:3000 if not provided)
const tracker = new WatchTimeTracker(process.env.WATCHTIME_API_URL || "http://localhost:3000");2. Get the API Version
Check the version of the backend service to ensure compatibility.
tracker.getVersion()
.then(version => {
console.log(`API Version: ${version}`);
})
.catch(error => {
console.error("Error fetching API version:", error);
});3. Publish an Event
Publish a single event for a user and content type. Timestamps are optional and default to the current time if omitted.
tracker.publishEvent("child1", "video", "2025-02-28T10:00:00Z")
.then(event => {
console.log("Event published:", event);
})
.catch(error => {
console.error("Error publishing event:", error);
});- Parameters:
userId: String (required, e.g.,"child1")contentType: String (required, e.g.,"video")timestamp: Optional ISO 8601 string (e.g.,"2025-02-28T10:00:00Z")
4. Publish a Watch Activity
Publish a complete watch activity by providing a start time and duration. This creates two events: one for the start and one for the end.
tracker.publishWatchActivity("child1", "video", "2025-02-28T10:00:00Z", 3600000) // 1 hour
.then(events => {
console.log("Activity published:", events);
})
.catch(error => {
console.error("Error publishing activity:", error);
});- Parameters:
userId: String (required)contentType: String (required)startTime: ISO 8601 string (required)duration: Number (milliseconds, required)
5. Get Watch Activities
Retrieve a list of watch activities for a user and content type within a time range. The library handles daily boundaries and open-ended activities automatically.
tracker.getWatchActivities(
"child1",
"video",
"2025-02-28T00:00:00Z",
"2025-02-28T23:59:59Z",
2 // Optional: reset activities at 2 AM UTC
)
.then(activities => {
console.log("Activities:", activities);
})
.catch(error => {
console.error("Error retrieving activities:", error);
});Parameters:
userId: String (required)contentType: String (required)startTime: ISO 8601 string (required)endTime: ISO 8601 string (required)dayBreakHour: Number (optional, default is 0 for midnight UTC)
Behavior:
- Activities are paired as start and end events.
- Open-ended activities (no end event) are closed at the end of the "activity day" if within the queried range.
- The "activity day" resets at the specified
dayBreakHour.
Advanced Usage
Custom Day Break Hour
Customize when an "activity day" resets by setting the dayBreakHour. For example, use 2 for 2 AM UTC.
tracker.getWatchActivities(
"child1",
"video",
"2025-02-28T00:00:00Z",
"2025-03-01T00:00:00Z",
2 // Reset at 2 AM UTC
)
.then(activities => {
console.log("Activities with custom day break:", activities);
});Error Handling
The library includes input validation and throws descriptive errors for invalid usage.
try {
await tracker.publishEvent("", "video"); // Throws error
} catch (error) {
console.error(error.message); // "userId must be a non-empty string"
}Configuration
Setting the API URL
Configure the backend service URL via the WATCHTIME_API_URL environment variable:
- Example
.envFile:WATCHTIME_API_URL=https://your-backend-url - Default: If unset, the library uses
http://localhost:3000.
Ensure this is set before initializing the library in your application.
Building and Publishing
To build and publish the watchtime-lib library to npm from your local setup (e.g., after running the setup script), follow these detailed steps:
Prerequisites
Install Node.js and npm:
- Ensure Node.js is installed on your Mac. You can check by running:
node -v npm -v - If not installed, download and install it from nodejs.org or use Homebrew:
brew install node
- Ensure Node.js is installed on your Mac. You can check by running:
Navigate to the Project Directory:
- After running the setup script, change into the project directory:
cd watchtime-lib
- After running the setup script, change into the project directory:
Install Dependencies:
- The
package.jsonspecifies TypeScript as a dev dependency. Install it by running:npm install - This creates a
node_modulesdirectory and installs TypeScript (~4.9.5 as specified).
- The
Build the Library
- Compile the TypeScript Code:
- Build the library into JavaScript files in the
distdirectory:npm run build - This runs the
tsccommand defined inpackage.json, generatingdist/index.js,dist/index.d.ts, and other compiled files.
- Build the library into JavaScript files in the
Publish to npm
Set Up an npm Account:
- If you don’t have an npm account, create one at npmjs.com.
- Log in to npm from your terminal:
npm login - Enter your username, password, and email when prompted.
Update Package Name (Optional):
- The default
nameinpackage.jsonis"watchtime-lib". Check if it’s available on npm:npm info watchtime-lib - If it’s taken, edit
package.jsonto use a unique name (e.g.,"@yourusername/watchtime-lib") before proceeding:"name": "@yourusername/watchtime-lib"
- The default
Publish the Library:
- Publish the package to npm:
npm publish --access public - The
--access publicflag is required for scoped packages (e.g.,@yourusername/watchtime-lib). For unscoped packages, you can omit it if it’s your first publish or configure it as public inpackage.json:"publishConfig": { "access": "public" }
- Publish the package to npm:
Verify Publication:
- Check npm to ensure your library is live:
npm info watchtime-lib - Or visit
https://www.npmjs.com/package/watchtime-lib(or your custom package name).
- Check npm to ensure your library is live:
Post-Publishing
- Version Updates (Optional):
- To update the library later, increment the
versioninpackage.json(e.g., from"1.0.0"to"1.0.1"), rebuild, and republish:npm run build npm publish --access public
- To update the library later, increment the
Notes
- Timestamps: Use ISO 8601 format (e.g.,
2025-02-28T10:00:00Z) for all timestamps. - Activity Days: Activities are grouped by "activity days," resetting at the
dayBreakHour(default is midnight UTC). - Open-Ended Activities: Activities without an end event are closed at the end of their "activity day" if within the query range; otherwise, they remain open.
This README.md provides everything you need to set up, use, and publish the watchtime-lib library effectively. Happy coding!
