npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mysql-crud-model

v1.1.14

Published

🍛基礎数据库读写 🍻getting獲取器 🥂setting設置器 🍾appending新增字段 🍷hideing過濾字段

Downloads

6

Readme

🫕 准备工作

** 🍴🍴🍴 使用npm或yarn安装 🍴🍴🍴 **

🥨 1. npm切换阿里镜像源

npm config set registry https://registry.nlark.com

🥖 2. 使用 npm

npm install mysql mysql-crud-model mysql-crud-core

🥯 3. yarn 安装

yarn add mysql mysql-crud-model mysql-crud-core

🍈 4. pnpm 安装

pnpm install mysql mysql-crud-model mysql-crud-core

🦪 开始使用

🍱 step1. 鏈接數據庫

  • 🍥 程序本身不具備鏈接數據庫的能力,
  • 🍫 需另外安裝 mysql 來鏈接數據并返回
/**
 * 🍱 創建鏈接池
 * */
import { createPool } from 'mysql';

const databaseConfig = {
    host: "<你的MySQL地址>",
    port: 3306, // 端口,可缺省默认 3306
    user: "<你的MySQL用戶名>",
    password: "<你的MySQL用戶密碼>",
    databas: "<數據庫名稱>"
}

const pool = createPool(databaseConfig);

console.log('🥗 數據庫鏈接成功');

🥟 step2. 定義自己的數據模型

import DataBaseModel from 'mysql-curd';

/**
 * 🔭 自定義BaseModel,並接受一個範型<T>
 * BaseModel不操作具體數據,只定義配置
 */
class BaseModel<T> extends DataBaseModel<T> {
    // 配置表前綴
    protected prefix: string = 'az_';
    constructor() {
        super(pool); // 傳入鏈接池
    }
}

/** 🥝 typescript定義了類型來描述表的字段 */
type Book = {
    id: number;
    cover: number;
    title: string;
    des: string;
    author: string;
    create_date: string;
    delete_date?: string;
};
// ✨✨✨BookModel 就是你的數據操作模型
class BookModel extends BaseModel<Book> {
    // 🍁 表名, 會自動加上表前綴,即真實表名為 `az_book`
    protected tableName: string = 'book';
}

🍧 setp3. 使用

🍚 數據插入

const book = new BookModel();
const result = await book.insert({
    cover: 1,
    title: '書本標題',
    des: '書本描述書本描述書本描述',
    author: '作者',
    create_date: '2022/12/15',
});

console.log('添加成功, 插入id:', result.insertId);

🍚🍚 插入多条

const book = new BookModel();
const result = await book.insert([
    {
        cover: 1,
        title: '書本標題',
        des: '書本描述書本描述書本描述',
        author: '作者',
        create_date: '2022/12/15',
    },
    {
        cover: 1,
        title: '書本標題',
        des: '書本描述書本描述書本描述',
        author: '作者',
        create_date: '2022/12/15',
    },
    {
        cover: 1,
        title: '書本標題',
        des: '書本描述書本描述書本描述',
        author: '作者',
        create_date: '2022/12/15',
    }
]);

🍭 數據查詢

selete 查询返回一组数据

const book = new BookModel();
const insertId = 1;
const result = await book.selete({
    where: {
        and: { id: insertId },
    },
});
// 🍌 如果查詢為空, 返回 null
console.log('🍌 id為1的數據', result);
🏺 find 查询单条
class BookModel extends BaseModel<Book> {
    protected tableName: string = 'book';
    // primaryKey默认值为 id
    // protected primaryKey: keyof Book = 'id';
}

const book = new BookModel();
// 查询id为1的单条数据,不存在返回null
const result = await book.find(1);
🧃 get 查询单条
// 查询id为1且delete_date為null的单条数据,不存在返回null
const result2 = await book.get({
    id: 1,
    delete_date: null
})

🍙 數據更新

const book = new BookModel();
const insertId = 1;
const result = await book.update(
    {
        title: '更新標題',
    },
    {
        where: {
            and: { id: insertId },
        },
    },
);
console.log('🍡更新結果', result);

🍂 数据删除

const book = new BookModel();
const result = await book._delete({
    where: {
        and: { id: insertId },
    },
});
console.log('🌶️ 删除数据結果', result);

🥥 where查询条件

查询条件可以是复杂的,可以是用and查询或or查询

🌰 简单查询

// 查询id等于1的数据
const where = {
    and: {
        id: 1
    }
}

🫘使用操作符号

🥦 OP.EQ 等于

import { OP } from 'mysql-crud-core/enum';
const where = {
    and: {
        id: [OP.EQ, 1]
    }
}

🥬 OP.NEQ 不等于

import { OP } from 'mysql-crud-core/enum';
const where = {
    and: {
        id: [OP.NEQ, 1]
    }
}

🥒 OP.GT 大于

import { OP } from 'mysql-crud-core/enum';
const where = {
    and: {
        id: [OP.GT, 1]
    }
}

🥑 OP.EGT 大于等于

import { OP } from 'mysql-crud-core/enum';
const where = {
    and: {
        id: [OP.EGT, 1]
    }
}

🍄 OP.LT 小于

import { OP } from 'mysql-crud-core/enum';
const where = {
    and: {
        id: [OP.LT, 1]
    }
}

🍅 OP.ELT 小于等于

import { OP } from 'mysql-crud-core/enum';
const where = {
    and: {
        id: [OP.ELT, 1]
    }
}

🫒 OP.LIKE 模糊查询

import { OP } from 'mysql-crud-core/enum';
const where = {
    and: {
        title: [OP.LIKE, '%花园%']
    }
}

🍆 OP.BETWEEN 区间查询

import { OP } from 'mysql-crud-core/enum';
const where = {
    and: {
        // 查询 id为 1~10之间对数据
        id: [OP.BETWEEN, [1, 10]]
    }
}

🌽 OP.NOT_BETWEEN 区间查询

import { OP } from 'mysql-crud-core/enum';
const where = {
    and: {
        // 查询 id不在 1~10之间对数据
        id: [OP.NOT_BETWEEN, [1, 10]]
    }
}

🌶️ OP.IN in查询

import { OP } from 'mysql-crud-core/enum';
const where = {
    and: {
        // 查询id为1 3 5 7
        id: [OP.IN, [1, 3, 5, 7]]
    }
}

🫑 OP.NOT_IN not in查询

import { OP } from 'mysql-crud-core/enum';
const where = {
    and: {
        // 查询id不为1 3 5 7
        id: [OP.NOT_IN, [1, 3, 5, 7]]
    }
}

🫐 复合查询

🍌🍌🍌 对于复杂的查询条件可以交叉使用 and 或 or 查询 🍌🍌🍌

🍓 and条件

and 须所有条件都满足

import { OP } from 'mysql-crud-core/enum';
// 
/**
 * id为 1 3 5 7 9 且 delet_date 为 NULL的数据
 * SQL: SELECT * FROM az_book WHERE `id` IN (1,3,5,7,9) AND `delete_date` IS NULL
 */
const result = await book.selete({
    where: {
        and: {
            id: [ OP.IN, [1, 3, 5, 7, 9] ],
            delete_date: null
        }
    }
})

🍑 or条件

or 仅需满足任意一个条件

import { OP } from 'mysql-crud-core/enum';
/**
 * id为 1 3 5 7 9 或者 delet_date 为 NULL的数据
 * SQL: SELECT * FROM az_book WHERE `id` IN (1,3,5,7,9) OR `delete_date` IS NULL
 */
const result = await book.selete({
    where: {
        or: {
            id: [ OP.IN, [1, 3, 5, 7, 9] ],
            delete_date: null
        }
    }
})

🍓and 与 🍑or 组合使用

import { OP } from 'mysql-crud-core/enum';

/**
 * (delete_date必须为null, cover不能为null) 并且 (title包含‘花园’二字 或者 id 大于 5)
 * SQl: SELECT * FROM az_book WHERE (`delete_date` IS NULL AND `cover` IS NOT NULL) AND (`title` LIKE '%花园' OR `id` > 5)
 */
const result1 = book.selete({
    where: {
        and: { 
            delete_date: null,
            cover: [OP.NEQ, null]
        },
        or: {
            title: [OP.LIKE, '%花园'],
            id: [OP.GT, 5]
        }
    },
})


/**
 * (delete_date必须为null, cover不能为null)或者(title包含‘花园’二字 或者 id 大于 5)
 * SQL: SELECT * FROM az_book WHERE (`delete_date` IS NULL AND `cover` IS NOT NULL) OR (`title` LIKE '%花园' OR `id` > 5)
 */
const result2 = book.selete({
    where: {
        and: { 
            delete_date: null,
            cover: [OP.NEQ, null]
        },
        or: {
            title: [OP.LIKE, '%花园'],
            id: [OP.GT, 5]
        }
    },
    join: 'OR'
})

🍐 orderBy 排序

// id 倒序
const result1 = book.selete({
    where: {
        and: { delete_date: null },
    },
    order: ['id', 'DESC']
});

// id 正序
const result2 = book.selete({
    where: {
        and: { delete_date: null },
    },
    order: ['id', 'ASC']
})

🍏 limit 获取指定条目

// 获取5条
const result1 = book.selete({
    where: {
        and: { delete_date: null },
    },
    limit: 5
})

// 从第5条开始再获取5条
const result2 = book.selete({
    where: {
        and: { delete_date: null },
    },
    limit: [5, 5]
})

🍺 getting hideing setting appending 字段操作

🍻 getting 在每次查詢返回結果時返回, 對結果再次進行清洗。 🍷 hideing 在每次查詢返回結果時檢查, hideing 數組中的字段將被過濾 🥂 setting 在寫入前觸發,返回結果將被寫入 🍾 appending 查詢返回的額外的字段

🍻 getting / hideing

详见Demo 🌰getting

/**
 * 定义模型时设置,添加对应操作
 * 🍷 hideing ['隐藏字段1', '隐藏字段2'...]
 * 🍻 getting 需要处理的字段信息
 */
class BookModel extends BaseModel<Book> {
    protected tableName: string = 'book';

    /** 隱藏字段信息 */
    readonly hideing: Array<keyof Book> = ['delete_date'];

    getting = {
        // create_date转为时间戳
        async create_date(
            val: string,
            key: 'create_date',
            data: Required<Book>,
        ) {
            const date = new Date(val);
            return date.getTime();
        },
    };
}

🥂setting

详见Demo 🌰setting

export class BookModel extends BaseModel<Book> {
    protected tableName: string = 'book';

    setting = {
        /** 統一插入時間的格式 */
        async create_date(val: string, key: 'create_date', data: Book) {
            const date = new Date(val ?? Date.now());
            const dateStr = [
                date.getFullYear(),
                date.getMonth() + 1,
                date.getDate(),
            ].join('-');
            return dateStr;
        },
    };
}

🍾 appending

详见Demo 🌰appending

export class BookModel extends BaseModel<Book> {
    protected tableName: string = 'book';
    /**
     * appending 可以理解为一些扩展字段
     */
    readonly appending = {
        async myData(data: Book) {
            return 6666;
        },
    };
}