A library for interacting with Apolitical APIs.
This library provides the ability to connect to our APIs. The main purpose is to create some structure around API requests and provide types for peace of mind ☀️
For more information about the underlying technology, visit ts-rest.
Consuming the client on the backend:
import { socialsApiContract } from '@apolitical/contracts';
import { nestControllerContract, NestRequestShapes } from '@ts-rest/nest';
const c = nestControllerContract(socialsApiContract);
type RequestShapes = NestRequestShapes<typeof c>;
@Controller()
export class UsersController implements NestControllerInterface<typeof c> {
constructor(private readonly usersService: UsersService) {}
@TsRest(c.updateUser)
async updateUser(@TsRestRequest() { body }: RequestShapes['updateUser']) {
const user = await this.usersService.updateUser({
name: body.name,
});
return { status: 201 as const, body: user }; // IMPORTANT: Always return the status and body
}
}
Consuming the client on the frontend:
// Import the contract and initClient
import { socialsApiContract } from '@apolitical/contracts';
import { initClient } from '@ts-rest/core';
// Initialise the API client
const client = initClient(socialsApiContract, {
baseUrl: 'https://apolitical.co/api/some-api', // Should come from config
baseHeaders: {
// Cookie: `apolitical_auth=${JWT}`, // Use this in a script context
// withCredentials: true // Use this on frontend
},
});
Run nx build contracts
to build the library.
Run nx test contracts
to execute the unit tests via Jest.