11.Effect Env Schema
เวลาเราจะกำหนดว่าใน ENV เราต้องมี data อะไรบ้าง เราก็จะใช้ tools พวก runtime validator มาช่วย
Effect เองก็มี tool แบบนั้นเช่นกัน และออกแบบมาเฉพาะทางให้ใช้กับ env โดยเฉพาะเลย
มาดูตัวอย่างกัน แต่ในตัวอย่างไม่ได้เกี่ยวกับ project ที่เราทำละ แต่ก็คิดว่าเห็นภาพเหมือนกัน
ในตัวอย่างจะสร้าง schema สำหรับ env เหล่านี้
.env
MINIO_HOST=localhostMINIO_PORT=9000MINIO_BUCKET_NAME=pdfMINIO_ACCESS_KEY=NHknhzKxHKpx5dMy3UlXMINIO_SECRET_KEY=rRc34UOLNrohu9dx0DhHh5Gdpn8sjRtp97IMfxqQMINIO_DOMAIN=http://localhost:9000
เราจะเขียน schema แบบนี้
import { Config } from "effect";
const minioConfig = Config.all({ accessKey: Config.string("ACCESS_KEY"), bucketName: Config.string("BUCKET_NAME"), domain: Config.string("DOMAIN"), host: Config.string("HOST"), port: Config.option(Config.integer("PORT")), secretKey: Config.string("SECRET_KEY")})
export const minioNestedConfig = Config.nested(minioConfig, "MINIO")
export const config = Config.all({ minio: minioNestedConfig,})
ตัวอย่างการใช้งาน
import { Effect, Option } from "effect"import * as Minio from "minio"
import { config } from "../config/index.js"
const getMinIOClientCurried = () => config.pipe( Effect.map(({ minio }) => { return new Minio.Client({ accessKey: minio.accessKey, endPoint: minio.host, port: Option.getOrElse(minio.port, () => undefined), secretKey: minio.secretKey, useSSL: false, }) }), Effect.map(client => { return () => client }))
export const getMinIOClient = getMinIOClientCurried()