Giter VIP home page Giter VIP logo

redbean-node's Introduction

RedBeanNode

npm pipeline status Coverage Status npm

⚠️Warning: Early Development. Do not use it on production!

RedBeanNode is an easy to use ORM tool for Node.js, strongly inspired by RedBeanPHP.

  • Automatically creates tables and columns as you go
  • No configuration, just fire and forget
  • Ported RedBeanPHP's main features and api design
  • Build on top of knex.js
  • Supports JavaScript & TypeScript
  • async/await or promise friendly

Supported Databases

  • MySQL / MariaDB
  • SQLite

Installation

npm install redbean-node --save

Read More

Docs: http://redbean-node.whatsticker.online

Playground

Try RedBeanNode in browser!

https://runkit.com/louislam/redbeannode-playground

Code Example

This is how you do CRUD in RedBeanNode:

const {R} = require("redbean-node");

// Setup connection
R.setup();

(async () => {
    let post = R.dispense('post');
    post.text = 'Hello World';

    // create or update
    let id = await R.store(post);

    // retrieve
    post = await R.load('post', id);

    console.log(post);

    // delete
    await R.trash(post);

    // close connection
    await R.close();
})();

This automatically generates the tables and columns... on-the-fly. It infers relations based on naming conventions.

Unit Test

Please build the project before run the test.

Additional

Icons made by Vitaly Gorbachev from https://www.flaticon.com

redbean-node's People

Contributors

kaysond avatar louislam avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

redbean-node's Issues

Автоматическая генерация плейсхолдеров .genSlots()

Дружище, спасибо за пакет!

В RedBeanPHP есть метод генерации плейсхолдеров для элементов массива ::genSlots()
https://redbeanphp.com/index.php?p=/finding
Увы, я не обнаружил этот метод в данном пакете.

Для себя на скорую руку набросал такую функцию, но надеюсь в скором времени метод R.genSlots() будет включен ваш пакет:

async function genSlots (array = []) {
  let placeholders = '';
  if (Array.isArray(array)) {
    let array_length = array.length;
    if (array_length) {
      for (let i = 0; i < array_length; i++) {
        placeholders += (i == array_length - 1) ? '?' : '?, ';
      }
    }
  }
  return placeholders;
}

isoDateTime() and isoTime() don't use milliseconds which causes issues for uptime-kuma push notifications

See louislam/uptime-kuma#1422 and louislam/uptime-kuma#1428

Without milliseconds in the format, the time information in the database can't be used to determine intervals <1 second. For example, if you have one event at 12:15:24.999 and another at 12:15:45.001, the database will record them as 12:15:24 and 12:15:45, showing a 21s time difference even though its much closer to 20s (20.002).

I think the best way to fix this is to add isoDateTimeMilliseconds() and isoTimeMilliseconds(), copying these functions

isoDateTime(dateTime : dayjs.Dayjs | Date | undefined = undefined) : string {
let dayjsObject;
if (dateTime instanceof dayjs) {
dayjsObject = dateTime;
} else {
dayjsObject = dayjs(dateTime);
}
return dayjsObject.format('YYYY-MM-DD HH:mm:ss');
}

isoTime(date : dayjs.Dayjs | Date | undefined = undefined) {
let dayjsObject;
if (date instanceof dayjs) {
dayjsObject = date;
} else {
dayjsObject = dayjs(date);
}
return dayjsObject.format('HH:mm:ss');
}

isDateTime(value : string) {
let format = "YYYY-MM-DD HH:mm:ss";
return dayjs(value, format).format(format) === value;
}

isTime(value : string) {
// Since dayjs is not supporting time only format, so prefix a fake date to parse
value = "2020-10-20 " + value;
let format = "YYYY-MM-DD HH:mm:ss";
return dayjs(value, format).format(format) === value;
}

We'd also need to update getDataType()

getDataType(value, fieldName : string = "") {

and isValidType()

isValidType(columnType, valueType) {

I may be missing some functions, particularly as far as the underlying db column type. I'm pretty sure mariadb supports milliseconds in datetime, and I believe sqlite just stores it as text so it should work no problem.

TypeError: 'set' on proxy: trap returned falsish for property

Hello, I am trying to create a simple relation but I am getting this very uninformative error.

This is the code:

    let car = db.R.dispense('car');
    car.brand = 'Brand';
    car.model = 'Model';
    car.year = 'Model';
    car.chat_keyword= 'KWD';
    try {await db.R.store(car);}catch (e) {console.log(e);}

    console.log("Creating usercar model");
    let usercar = db.R.dispense('usercar');
    usercar.added_date = db.R.isoDate();
    usercar.car = car;
    try {await db.R.store(usercar);}catch (e) {console.log(e);}

Error:

TypeError: 'set' on proxy: trap returned falsish for property 'carId'
    at Proxy.<anonymous> (C:\Users\Perroloco\Programming\node\evsyscheduler\node_modules\redbean-node\dist\bean.js:187:57)
    at Generator.next (<anonymous>)
    at C:\Users\Perroloco\Programming\node\evsyscheduler\node_modules\redbean-node\dist\bean.js:14:71
    at new Promise (<anonymous>)
    at __awaiter (C:\Users\Perroloco\Programming\node\evsyscheduler\node_modules\redbean-node\dist\bean.js:10:12)
    at Proxy.storeTypeBeanList (C:\Users\Perroloco\Programming\node\evsyscheduler\node_modules\redbean-node\dist\bean.js:180:16)
    at RedBeanNode.<anonymous> (C:\Users\Perroloco\Programming\node\evsyscheduler\node_modules\redbean-node\dist\redbean-node.js:126:24)
    at Generator.next (<anonymous>)
    at C:\Users\Perroloco\Programming\node\evsyscheduler\node_modules\redbean-node\dist\redbean-node.js:8:71
    at new Promise (<anonymous>)
    at __awaiter (C:\Users\Perroloco\Programming\node\evsyscheduler\node_modules\redbean-node\dist\redbean-node.js:4:12)
    at RedBeanNode.storeCore (C:\Users\Perroloco\Programming\node\evsyscheduler\node_modules\redbean-node\dist\redbean-node.js:124:16)
    at RedBeanNode.<anonymous> (C:\Users\Perroloco\Programming\node\evsyscheduler\node_modules\redbean-node\dist\redbean-node.js:116:35)
    at Generator.next (<anonymous>)
    at fulfilled (C:\Users\Perroloco\Programming\node\evsyscheduler\node_modules\redbean-node\dist\redbean-node.js:5:58)

Am I doing something wrong? thx

Make sqlite /other db optional

I think its a good idea to optionally install other databases just like what knex did. I cant even install because i dont have visual studio build tools which sqlite requires.

Ошибка в форматировании запроса

const admins = await R.findAll('users', 'server_number = ? AND admin_level >= ?', [user.server_number, 1]);

Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server at Sequence._packetToError (/VKBot/node_modules/mysql/lib/protocol/sequences/Sequence.js:47:14) at Query.ErrorPacket (/VKBot/node_modules/mysql/lib/protocol/sequences/Query.js:79:18) at Protocol._parsePacket (/VKBot/node_modules/mysql/lib/protocol/Protocol.js:291:23) at Parser._parsePacket (/VKBot/node_modules/mysql/lib/protocol/Parser.js:433:10) at Parser.write (/VKBot/node_modules/mysql/lib/protocol/Parser.js:43:10) at Protocol.write (/VKBot/node_modules/mysql/lib/protocol/Protocol.js:38:16) at Socket.<anonymous> (/VKBot/node_modules/mysql/lib/Connection.js:88:28) at Socket.<anonymous> (/VKBot/node_modules/mysql/lib/Connection.js:526:10) at Socket.emit (node:events:518:28) at addChunk (node:internal/streams/readable:559:12) -------------------- at Protocol._enqueue (/VKBot/node_modules/mysql/lib/protocol/Protocol.js:144:48) at Connection.query (/VKBot/node_modules/mysql/lib/Connection.js:198:25) at /VKBot/node_modules/knex/lib/dialects/mysql/index.js:132:18 at new Promise (<anonymous>) at Client_MySQL._query (/VKBot/node_modules/knex/lib/dialects/mysql/index.js:126:12) at executeQuery (/VKBot/node_modules/knex/lib/execution/internal/query-executioner.js:37:17) at Client_MySQL.query (/VKBot/node_modules/knex/lib/client.js:146:12) at Runner.query (/VKBot/node_modules/knex/lib/execution/runner.js:123:36) at ensureConnectionCallback (/VKBot/node_modules/knex/lib/execution/internal/ensure-connection-callback.js:13:17) at Runner.ensureConnection (/VKBot/node_modules/knex/lib/execution/runner.js:300:20) { code: 'ER_PARSE_ERROR', errno: 1064, sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version sqlState: '42000', index: 0, sql: 'select * from users where 1=1 server_number = 1 AND admin_level >= 1'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.