iTranslated by AI
Creating Custom Badges with Shields.io and Cloudflare Workers
Out of the blue, I've created something like this.
This is a Chunithm[1] rating display badge—I'm probably the only one in the world doing this!!!! (I'm only providing the URL since images would be saved to Zenn's servers.)
It updates correctly. At the time of writing, it's 15.56, but it will likely have changed by the time you see it.
So, I decided to try making a custom shields.io badge using Cloudflare Workers.
What are Custom Badges Anyway?
There are two types of custom badges on shields.io: those that retrieve data from JSON/XML/YAML by specifying a path, and those that retrieve data from an endpoint that returns JSON matching a specific schema.
The former allows you to, for example, create a follower badge by fetching followers from an ActivityPub URL.
This time, I'll be using the latter.
What is a JSON Endpoint Badge?
These badges are specified like https://img.shields.io/endpoint?url=...&style=....
According to the official documentation[2], this approach is superior to redirecting for the following reasons (summarized):
- The mechanism for returning content is separated from the mechanism for displaying it. As an API developer, you only need to think about the content of the badge, without worrying about styles and such.
- You can always use the latest badge display style. There's no need to keep up with badge templates or npm packages.
- A mechanism that returns JSON is easier to create than a redirect. Most frameworks support it.
- You can take advantage of the Shields CDN. You don't need to learn the intricacies of HTTP caching; you can tune caching behavior just by adding properties to the JSON.
What Should You Return?
type Response = {
// Badge schema version. Always "1".
schemaVersion: number;
// Left-side text. Empty string if omitted.
// Can be overridden via URL query.
label?: string;
// Right-side text. Must be specified.
message: string;
// Right-side color. Can be specified like "Colors" at the bottom of the shields.io homepage.
// Can be overridden via URL query.
color?: string;
// Left-side color. Can be overridden via URL query.
labelColor?: string;
// Set to true to treat as an error badge. In this case, the user cannot override the color.
// May also affect cache behavior.
isError?: boolean;
// Logo name. Must be a logo name supported by Shields or simple-icons.
// Can be overridden via URL query.
namedLogo?: string;
// SVG string representing a custom logo.
// Can be overridden via URL query.
logoSvg?: string;
// Logo color. Only applies to namedLogo and Shields logos.
// Can be overridden via URL query.
logoColor?: string;
// Logo width. Can be overridden via URL query.
logoWidth?: string;
// Logo position. Can be overridden via URL query.
logoPosition?: string;
// Display style. Defaults to "flat".
// Can be overridden via URL query.
style?: string;
// HTTP cache lifetime (in seconds). Used for Shields CDN and the browser.
// Values less than 300 are ignored.
// The specified value can be overridden via URL query, but only longer values are allowed.
// Allows for performance and traffic tuning.
cacheSeconds?: number;
}
Creating an API with Cloudflare Workers
- Install wrangler via npm.
$ npm i -g wrangler
- Link wrangler with your Cloudflare account.
$ wrangler login
- Create a project.
$ wrangler init my-app
$ cd my-app
- Debug the Workers.
$ wrangler dev
Here is a sample for the Chunirec badge.
import svg from "./chuni.svg.txt"; // Note: Can only be imported if it's .txt or .html
interface Player {
user_id: number;
player_name: string;
title: string;
title_rarity: string;
level: number;
rating: number;
rating_max: number;
classemblem: string | null;
classemblem_base: string | null;
is_joined_team: boolean;
updated_at: string;
}
export default {
async fetch(
request: Request,
env: {
CHUNIREC_API_KEY: string;
}
) {
const url = new URL("https://api.chunirec.net/2.0/records/profile.json");
url.searchParams.set("token", env.CHUNIREC_API_KEY);
url.searchParams.set("region", "jp2");
const player = (await fetch(url.toString(), {
// Enable caching
cf: {
cacheEverything: true,
cacheTtl: 60 * 5,
},
}).then((res) => res.json())) as Player;
return new Response(
JSON.stringify({
schemaVersion: 1,
label: player.player_name
.replace(/[A-Za-z0-9]/g, (s) => {
return String.fromCharCode(s.charCodeAt(0) - 0xfee0);
})
.replace(".", "."),
message: player.rating,
color: "ffe795",
logoSvg: svg,
})
);
},
};
- Deploy.
$ wrangler publish
Your Worker's URL should be displayed here.
Testing the Badge
There is a testing form at the bottom of the JSON endpoint badge documentation. If you paste your Worker's URL there, you should be able to see the badge in action.
Conclusion
Cloudflare Workers was easier than I expected. I'd like to try making other badges in the future.
Thank you.
-
Strictly speaking, Chunirec ↩︎
Discussion