Contract First and @feelai/contract: A New Approach for Data-Type Safe Application Development
In today's modern software development world, ensuring consistency between client and server is a significant challenge. The Contract First method has emerged as an effective solution, and is now strongly supported by the @feelai/contract library.
Contract First is a software development methodology where the application programming interface (API) definition is established before detailed implementation. Instead of writing code first and then defining the API, this method requires:
Benefits of Contract First include:
@feelai/contract is an npm library that facilitates the implementation of the Contract First methodology in TypeScript projects. This library provides tools to define API contracts in a type-safe manner, which can be shared between client and server without circular dependency issues.
typebox for schema definitionbun add @feelai/contract
# or
npm install @feelai/contract
# or
yarn add @feelai/contractHere is an example contract definition for a task management application:
import { Contract, defineApiMap, defineSocketMap } from "@feelai/contract";
import { Type } from "typebox";
// Define schemas
export const TaskSchema = Type.Object({
id: Type.String(),
title: Type.String(),
completed: Type.Boolean(),
createdAt: Type.Number(),
});
// Define API endpoints
const api = defineApiMap({
getTasks: {
output: Type.Array(TaskSchema),
},
createTask: {
input: Type.Object({
title: Type.String(),
}),
output: TaskSchema,
},
});
// Define Socket events
const socket = defineSocketMap({
taskUpdates: {
client: {
subscribe: Type.Object({}),
},
server: {
taskCreated: TaskSchema,
taskUpdated: TaskSchema,
},
},
});
// Create and export the contract
export const todoListContract = new Contract().api(api).socket(socket);
export type TodoListContract = typeof todoListContract;One of the strengths of @feelai/contract is its automatic type inference capability:
import { StaticApiMap, StaticSocketMap } from "@feelai/contract";
import { todoListContract } from "./todoListContract";
// Types for API implementation
export type ApiTypes = StaticApiMap<typeof todoListContract>;
// Types for Socket implementation
export type SocketTypes = StaticSocketMap<typeof todoListContract>;The Contract First methodology combined with the @feelai/contract library offers a structured approach to modern web application development. With its ability to ensure end-to-end data type safety, minimize client-server communication errors, and support parallel development, it is a valuable tool for TypeScript projects of medium to large scale.
To learn more about @feelai/contract, visit: https://www.npmjs.com/package/@feelai/contract