1 import { v2 as cloudinary } from "cloudinary"
2
3 export type UploadResult = {
4 /** The `https` delivery URL to reference from the release notes. */
5 url: string
6 /** Full public ID, folder included. */
7 publicId: string
8 }
9
10 /**
11 * Reads Cloudinary credentials from the environment.
12 *
13 * `CLOUDINARY_URL` is the SDK's own convention and keeps this to a single
14 * secret; the three separate variables are accepted as a fallback.
15 */
16 function configure(): void {
17 if (process.env.CLOUDINARY_URL) {
18 // The SDK parses CLOUDINARY_URL by itself.
19 cloudinary.config(true)
20 return
21 }
22
23 const cloudName = process.env.CLOUDINARY_CLOUD_NAME
24 const apiKey = process.env.CLOUDINARY_API_KEY
25 const apiSecret = process.env.CLOUDINARY_API_SECRET
26
27 if (!cloudName || !apiKey || !apiSecret) {
28 throw new Error(
29 "Missing Cloudinary credentials: set CLOUDINARY_URL, or all of " +
30 "CLOUDINARY_CLOUD_NAME, CLOUDINARY_API_KEY and CLOUDINARY_API_SECRET."
31 )
32 }
33
34 cloudinary.config({
35 cloud_name: cloudName,
36 api_key: apiKey,
37 api_secret: apiSecret,
38 secure: true,
39 })
40 }
41
42 /**
43 * Uploads a banner to a folder in the media library and returns its delivery
44 * URL. The folder and public ID come from the banner's definition.
45 *
46 * Uploading to a public ID that already exists overwrites it in place, and
47 * `invalidate` purges the CDN so the new image is actually served. The CLI gives
48 * every upload its own suffixed ID, so in practice that path is only taken if a
49 * caller passes an ID of its own.
50 */
51 export async function uploadBanner({
52 png,
53 folder,
54 publicId,
55 }: {
56 png: Buffer
57 folder: string
58 publicId: string
59 }): Promise<UploadResult> {
60 configure()
61
62 const result = await cloudinary.uploader.upload(
63 `data:image/png;base64,${png.toString("base64")}`,
64 {
65 folder,
66 public_id: publicId,
67 resource_type: "image",
68 overwrite: true,
69 invalidate: true,
70 }
71 )
72
73 return { url: result.secure_url, publicId: result.public_id }
74 }