Neurosis Prevention Mechanism

    winter-cobbler
    TypeScript icon, indicating that this package has built-in type declarations

    0.0.13 • Public • Published

    Winter Cobbler - Simple json file based Rest Data API

    Working like a simple db backend with Rest API - save and load only json files.

    Usage

    package.json

    {
    	"scripts": {
    		"server": "ts-node -P ./server/server.tsconfig.json ./server/index.ts"
    	},
    	"devDependencies": {
    		"winter-cobbler": "0.0.7"
    	}
    }

    cobbler.json

    {
    	"port": 7121,
    	"path": "./sample",
    	"url": "/api/",
    	"basicAuth": { "users": { "admin": "qwer123", "c_miriam": "123" } }
    }

    server/server.tsconfig.json

    {
    	"compilerOptions": {
    		"module": "commonjs",
    		"lib": ["es2020"],
    		"target": "es2020"
    	}
    }

    server/index.ts

    import { Serve, Cobbler, CobblerHandler } from 'winter-cobbler';
    import { Express } from 'express';
    
    class AppHandler extends CobblerHandler {
    	cobbler: Cobbler;
    
    	afterInit(cobbler: Cobbler) {
    		this.cobbler = cobbler;
    	}
    
    	initExpress(app: Express) {
    		app.get('/checkAuth', (req, res) => {
    			const userNick = (req as any).auth.user;
    
    			const found = this.cobbler.findAll('users', {
    				nick_equal: userNick,
    			});
    
    			if (found.length) {
    				res.json(found[0]);
    			} else {
    				res.json({
    					nick: userNick,
    					id: -1,
    					message: 'Not in table!',
    				});
    			}
    		});
    	}
    }
    
    const handler = new AppHandler();
    
    Serve(handler);

    Simple Upload handling

    import * as multer from 'multer';
    import { randomUUID } from 'crypto';
    
    // https://expressjs.com/en/resources/middleware/multer.html
    const upload = multer({
    	storage: multer.diskStorage({
    		destination: (req, file, cb) => {
    			cb(null, 'sample/files');
    		},
    		filename: (req, file, cb) => {
    			const original = file.originalname.replace(/[^a-zA-Z0-9\.]/g, '_');
    
    			cb(null, `${randomUUID()}-${original}`);
    		},
    	}),
    } as multer.Options);
    
    class AppHandler extends CobblerHandler {
    	// ...
    	initExpress(app: Express) {
    		app.post('/upload', upload.single('file'), function (req, res, next) {
    			// req.body will hold the text fields, if there were any
    			const file: Express.Multer.File = (req as any).file;
    
    			console.log(file, req.body);
    
    			res.json({
    				success: true,
    				file: { path: file.filename, size: file.size },
    			});
    		});
    		// ...
    	}
    }

    Keywords

    none

    Install

    npm i winter-cobbler

    DownloadsWeekly Downloads

    6

    Version

    0.0.13

    License

    ISC

    Unpacked Size

    34.5 kB

    Total Files

    14

    Last publish

    Collaborators

    • godzzo