cca-image-module
v0.0.35
Published
Image module
Readme
cca-image-module
Image management module for Node.js. It provides upload, retrieval, update, and delete operations with AWS S3 storage, pagination, and optional relations.
Installation
npm install cca-image-moduleExports
import { createImageContainer, ImageController, S3Config, s3ConfigManager } from "cca-image-module";Setup
- Configure S3 (must be done before creating the container):
import { s3ConfigManager, S3Config } from "cca-image-module";
import "dotenv/config";
const s3Config: S3Config = {
accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
region: process.env.AWS_REGION!,
bucket: process.env.AWS_S3_BUCKET!,
};
s3ConfigManager.setConfig(s3Config);Required env vars:
AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEYAWS_REGIONAWS_S3_BUCKET
If you want to load config asynchronously, you can set it later and the module will wait for it.
Just make sure s3ConfigManager.setConfig(...) is called before createImageContainer(...) runs.
- Create container and controller:
import { createImageContainer } from "cca-image-module";
// Use your own BaseDatabase implementation from cca-core
const database = new YourDatabase(/* your connection manager */);
const { imageController } = await createImageContainer(database);- Wire routes (Express + Multer):
import express from "express";
import multer from "multer";
const app = express();
const upload = multer({ dest: "uploads/" });
app.use(express.json());
app.post("/images", upload.single("file"), imageController.createImage);
app.post("/images/bulk", upload.array("files"), imageController.createImages);
app.get("/images/:id", imageController.getImage);
app.get("/images", imageController.getAllImages);
app.get("/images/categories/:id", imageController.getCategoryImages);
app.get("/images/posts/:id", imageController.getPostImages);
app.get("/images/authors/:id", imageController.getAuthorImages);
app.put("/images/:id", imageController.updateImage);
app.delete("/images/:id", imageController.deleteImage);
app.delete("/images", imageController.deleteImages);
app.use((err, req, res, next) => {
res.status(err?.statusCode ?? 500).json({ error: err?.message ?? "Server error" });
});API Notes
sizemust be one of:original,thumb,sm,md,lg,xl.- For bulk upload:
filesis an array of files.sizecan be a single string (applies to all files) or an array matching the files count.
- Update:
sizeselects which URL field to update.title,description,categoryId,postIdcan be updated without uploading a new file.
Endpoints Summary
POST /images- create one image (multipart/form-data,filefield)POST /images/bulk- create multiple images (multipart/form-data,filesfield)GET /images/:id- get by idGET /images- paginated listGET /images/categories/:id- by categoryGET /images/posts/:id- by postGET /images/authors/:id- by authorPUT /images/:id- updateDELETE /images/:id- delete oneDELETE /images- delete many ({ ids: string[] })
License
ISC. See LICENSE.txt.
