iTranslated by AI
Comfortable Schema-Driven Development with openapi2aspida
Purpose of This Article
Development using auto-generated types via openApi2aspida was quite comfortable, so I would like to introduce its benefits and useful points.
Introduction
In frontend development, you might occasionally find yourself writing backend response types in a types folder.
For example, when receiving a response like the following for user information:
// types/user.ts
type User = {
id: stirng;
name: string;
role: 'admin' | 'free';
};
You would define a type like the one above and use it in your components.
import { User } from '@/types/user';
export const UserInfo = (props: User) => {
// ....
};
Using openApi2aspida eliminates the need for this manual type definition step and can prevent mistakes such as property name typos by frontend developers.
Also, in openApi2aspida, by gathering type information in the OpenAPI components (FYI: https://swagger.io/docs/specification/components/ ), a @types folder like the one below is generated.
├── $api.ts
├── @types
│ └── index.ts
├── comments
│ ├── $api.ts
│ └── index.ts
└── posts
├── $api.ts
├── _id@string
│ └── index.ts
└── index.ts
The contents of the @types folder look like this:
// Automatically generated
/* eslint-disable */
export type Post = {
id: number;
title: string;
author: string;
};
export type Comment = {
id: number;
body: string;
postId: number;
};
By developing the frontend using these auto-generated types, you can proceed without manually defining types yourself.
Furthermore, even when there are changes in the backend response, if you update the definition written in OpenAPI and regenerate the types using openapi2aspida, the contents of the @types folder will be updated automatically. This prevents discrepancies between the response contents on the frontend and backend.
About aspida
Regarding what aspida is in the first place, the author has created an easy-to-understand article. You can basically understand how to use it and the merits of the library by looking at that article.
As for openapi2aspida, just as stated in the README.md, using it like npx openapi2aspida -i https://petstore.swagger.io/v2/swagger.json will create aspida type definitions from the API definition.
Useful Points
Peace of Mind from Generated Types
Since you don't need to manually define types for API responses and can implement based on the definitions written in OpenAPI, you can focus on implementing logic without worrying about property name mistakes, as long as the OpenAPI definition is correct.
The following point is raised as an issue in the article above:
Type definitions on the API side and the frontend side are not synchronized, so type definition files currently exist for each. We are considering unifying these double-managed type definitions by using OpenAPI or similar in the future.
By establishing specifications in OpenAPI between the backend and frontend teams and managing the definitions centrally, we were able to proceed with schema-driven development and felt a tangible increase in development speed.
No Need to Write Mock Responses for Tests
Writing API responses in tests is a common task.
When testing components that display or use data, you often define responses. Even when using MSW, you might write the JSON content as follows:
rest.get('/user', (req, res, ctx) => {
return res(
ctx.json({
firstName: 'John',
age: 38,
})
);
});
As shown above, you often describe the content of the JSON. By using the OpenAPI example (https://swagger.io/docs/specification/adding-examples/ ) for this response, you no longer need to define the response yourself.
To achieve this, it is preferable to write OpenAPI in JSON format. You can import the JSON and use the example values like this:
import schema from '../schema/api.json';
...
rest.get('/posts', (req, res, ctx) => {
return res(ctx.status(200), ctx.json(schema.components.schemas.Post['x-examples']['example-3']));
}),
...
Since the schema.schema.... part is long, it is better to extract it into a file like components.ts for use.
import schema from '../schema/api.json';
const components = {
Posts: [
schema.components.schemas.Post['x-examples']['example-1'],
schema.components.schemas.Post['x-examples']['example-2'],
schema.components.schemas.Post['x-examples']['example-3'],
],
Post: schema.components.schemas.Post['x-examples']['example-1'],
};
export default components;
Defining a handler using these components would look like this:
// handlers.ts
import { rest } from 'msw';
import { Post } from '../api/@types';
import components from './components';
export const handlers = [
// Fetch post list
rest.get('/posts', (req, res, ctx) => {
return res(ctx.status(200), ctx.json(components.Posts));
}),
Something like this.
This method was introduced in this article, which I found very helpful.
Even when using jest.mock instead of MSW, you can use components as follows to avoid writing individual responses:
jest.mock('@/utils/api.ts', () => ({
$axios: {
$get: jest.fn(() => Promise.resolve(components.Posts)),
},
}));
Summary
This article explained how to achieve comfortable frontend development using openapi2aspida. In cases where GraphQL is used for development, tools like GraphQL Code Generator may allow for more strictly typed development. However, when GraphQL cannot be used on the backend due to resource constraints or other factors, the openapi2aspida-based approach introduced here can provide a comfortable schema-driven development experience.
That concludes my thoughts on the benefits of schema-driven development using openapi2aspida.
Code
- source: nextjs-app-with-openapi
References
Discussion