Skip to content

TekuConcept/casl-bridge

Folders and files

NameName
Last commit message
Last commit date

Latest commit

a85e12e · May 7, 2024

History

36 Commits
May 7, 2024
May 7, 2024
Apr 13, 2024
Apr 13, 2024
Apr 13, 2024
May 1, 2024
Apr 13, 2024
Apr 13, 2024
May 7, 2024
May 7, 2024
Apr 14, 2024
Apr 13, 2024
Apr 13, 2024

Repository files navigation

casl-bridge

NPM Latest Release Coverage

A query bridge between CASL rules and TypeORM

Installation

This is a module available through the npm registry.

$ npm install casl-bridge

Examples

A simple demonstration...

async function main() {
    const source = getTypeOrmSource()
    const builder = new AbilityBuilder(createMongoAbility)

    builder.can('read', 'Book', { id: 1 })
    builder.can('read', 'Book', { 'author.id': 3 })

    const ability = builder.build()

    /* --------------------------------------
     * link everything together with a bridge
     */

    const bridge = new CaslBridge(source, ability)
}

Basic Calls

/* --------------------------------------
 * query all entries
 */

const books = await bridge
    .createQueryTo('read', 'Book')
    .getMany()

/* --------------------------------------
 * query a single field
 */

const ids = await bridge
    .createQueryTo('read', 'Book', 'id')
    .getMany()

/* --------------------------------------
 * select specific fields
 */

const select = ['id', 'title', ['author', ['name']]]
const names = await bridge
    .createQueryTo('read', 'Book', select)
    .limit(3)
    .getMany()

/* --------------------------------------
 * add extra mongo-like query filters
 */

const filter = { id: { $ge: 10, $le: 20 } }
const limited = await bridge
    .createQueryTo('read', 'Book', select, filter)
    .limit(3)
    .getMany()

/* --------------------------------------
 * using just the filter feature
 */

const filtered = await bridge
    .createFilterFor('Book', {
        'author.name': 'Jane Austen',
        id: { $in: [2, 3, 5] },
    })
    .getMany()

/* --------------------------------------
 * [experimental] apply filter to query
 */

const query = bookRepo
    .createQueryBuilder('book')
    .leftJoin('book.author', 'author')
    .where('book.id > :bookId', { bookId: 3 })

bridge.applyFilterTo(query, 'author', {
    name: 'Jane Austen'
})

const moreBooks = await query.getOne()

Database Setup

import { DataSource } from 'typeorm'

/* --------------------------------------
 * Our TypeOrm database connection
 */

const source = new DataSource({
    type: 'better-sqlite3',
    database: ':memory:',
    dropSchema: true,
    synchronize: true,
    entities: [
        AuthorSchema,
        BookSchema
    ],
})

async function connect() {
    await source.initialize()

    /* --------------------------------------
     * ...seed your database here
     */
}

About

A query bridge between CASL rules and database ORMs

Resources

License

Stars

Watchers

Forks

Packages

No packages published