Giter Site home page Giter Site logo

remult / remult Goto Github PK

View Code? Open in Web Editor NEW
2.7K 29.0 116.0 40.26 MB

Full-stack CRUD, simplified, with SSOT TypeScript entities

Home Page: https://remult.dev

License: MIT License

TypeScript 98.51% JavaScript 0.63% HTML 0.02% Shell 0.02% CSS 0.80% Svelte 0.01% Vue 0.01%
typescript postgresql fullstack crud orm validation fullstack-typescript api rest express-middleware

remult's Introduction

Remult

Full-stack CRUD, simplified, with SSOT TypeScript entities

CircleCI GitHub license npm version npm downloads Join Discord



What is Remult?

Remult uses TypeScript entities as a single source of truth for: ✅ CRUD + Realtime API, ✅ frontend type-safe API client, and ✅ backend ORM.

  • Zero-boilerplate CRUD + Realtime API with paging, sorting, and filtering
  • 👌 Fullstack type-safety for API queries, mutations and RPC, without code generation
  • ✨ Input validation, defined once, runs both on the backend and on the frontend for best UX
  • 🔒 Fine-grained code-based API authorization
  • 😌 Incrementally adoptable

Remult supports all major databases, including: PostgreSQL, MySQL, SQLite, MongoDB, MSSQL and Oracle.

Remult is frontend and backend framework agnostic and comes with adapters for Express, Fastify, Next.js, Nuxt, SvelteKit, SolidStart, Nest, Koa, Hapi and Hono.

Remult promotes a consistent query syntax for both frontend and Backend code:

// Frontend - GET: /api/products?_limit=10&unitPrice.gt=5,_sort=name
// Backend  - 'select name, unitPrice from products where unitPrice > 5 order by name limit 10'
await repo(Product).find({
  limit: 10,
  orderBy: {
    name: 'asc',
  },
  where: {
    unitPrice: { $gt: 5 },
  },
})

// Frontend - PUT: '/api/products/product7' (body: { "unitPrice" : 7 })
// Backend  - 'update products set unitPrice = 7 where id = product7'
await repo(Product).update('product7', { unitPrice: 7 })

Usage

Define schema in code

// shared/product.ts

import { Entity, Fields } from 'remult'

@Entity('products', {
  allowApiCrud: true,
})
export class Product {
  @Fields.cuid()
  id = ''

  @Fields.string()
  name = ''

  @Fields.number()
  unitPrice = 0
}

Add backend API with a single line of code

Example:

// backend/index.ts

import express from 'express'
import { remultExpress } from 'remult/remult-express' // adapters for: Fastify,Next.js, Nuxt, SvelteKit, SolidStart, Nest, more...
import { createPostgresDataProvider } from 'remult/postgres' // supported: PostgreSQL, MySQL, SQLite, MongoDB, MSSQL and Oracle
import { Product } from '../shared/product'

const app = express()

app.use(
  remultExpress({
    entities: [Product],
    dataProvider: createPostgresDataProvider({
      connectionString: 'postgres://user:password@host:5432/database"',
    }),
  }),
)

app.listen()

Remult adds route handlers for a fully functional REST API and realtime live-query endpoints, optionally including an Open API spec and a GraphQL endpoint

Fetch data with type-safe frontend code

const [products, setProducts] = useState<Product[]>([])

useEffect(() => {
  repo(Product)
    .find({
      limit: 10,
      orderBy: {
        name: 'asc',
      },
      where: {
        unitPrice: { $gt: 5 },
      },
    })
    .then(setProducts)
}, [])

📣 Realtime Live Queries

useEffect(() => {
  return repo(Product)
    .liveQuery({
      limit: 10,
      orderBy: {
        name: 'asc',
      },
      where: {
        unitPrice: { $gt: 5 },
      },
    })
    .subscribe((info) => {
      setProducts(info.applyChanges)
    })
}, [])

☑️ Data validation and constraints - defined once

import { Entity, Fields, Validators } from 'remult'

@Entity('products', {
  allowApiCrud: true,
})
export class Product {
  @Fields.cuid()
  id = ''

  @Fields.string({
    validate: Validators.required,
  })
  name = ''

  @Fields.number<Product>({
    validate: (product) => product.unitPrice > 0 || 'must be greater than 0',
  })
  unitPrice = 0
}

Enforced in frontend:

try {
  await repo(Product).insert({ name: '', unitPrice: -1 })
} catch (e: any) {
  console.error(e)
  /* Detailed error object ->
{
  "modelState": {
    "name": "Should not be empty",
    "unitPrice": "must be greater than 0"
  },
  "message": "Name: Should not be empty"
}
*/
}

Enforced in backend:

// POST '/api/products' BODY: { "name":"", "unitPrice":-1 }
// Response: status 400, body:
{
  "modelState": {
    "name": "Should not be empty",
    "unitPrice": "must be greater than 0"
  },
  "message": "Name: Should not be empty"
}

🔒 Secure the API with fine-grained authorization

@Entity<Article>('Articles', {
  allowApiRead: true,
  allowApiInsert: Allow.authenticated,
  allowApiUpdate: (article) => article.author == remult.user.id,
  apiPrefilter: () => {
    if (remult.isAllowed('admin')) return {}
    return {
      author: remult.user.id,
    }
  },
})
export class Article {
  @Fields.string({ allowApiUpdate: false })
  slug = ''

  @Fields.string({ allowApiUpdate: false })
  authorId = remult.user!.id

  @Fields.string()
  content = ''
}

🚀 Relations

await repo(Categories).find({
  orderBy: {
    name: 'asc ',
  },
  include: {
    products: {
      where: {
        unitPrice: { $gt: 5 },
      },
    },
  },
})

// Entity Definitions
export class Product {
  //...
  @Relations.toOne(Category)
  category?: Category
}
export class Category {
  //...
  @Relations.toMany<Category, Product>(() => Product, `category`)
  products?: Product[]
}

Automatic admin UI

Automatic admin UI

What about complex CRUD?

While simple CRUD shouldn’t require any backend coding, using Remult means having the ability to handle any complex scenario by controlling the backend in numerous ways:

  • Backend computed (read-only) fields - from simple expressions to complex data lookups or even direct db access (SQL)
  • Custom side-effects with entity lifecycle hooks (before/after saving/deleting)
  • Backend only updatable fields (e.g. “last updated at”)
  • Relations
  • Roll-your-own type-safe endpoints with Backend Methods
  • Roll-your-own low-level endpoints (Express, Fastify, koa, others…)

Installation

The remult package is one and the same for both the frontend bundle and the backend. Install it once for a monolith project or per-repo in a monorepo.

npm i remult

Tutorials

The best way to learn Remult is by following a tutorial of a simple Todo web app with a Node.js Express backend.

Demo

Video thumbnail

Watch code demo on YouTube here (14 mins)

Documentation

The documentation covers the main features of Remult. However, it is still a work-in-progress.

Example Apps

Status

Remult is production-ready and, in fact, used in production apps since 2018. However, we’re keeping the major version at zero so we can use community feedback to finalize the v1 API.

Motivation

Full-stack web development is (still) too complicated. Simple CRUD, a common requirement of any business application, should be simple to build, maintain, and extend when the need arises.

Remult abstracts away repetitive, boilerplate, error-prone, and poorly designed code on the one hand, and enables total flexibility and control on the other. Remult helps building fullstack apps using only TypeScript code you can easily follow and safely refactor, and fits nicely into any existing or new project by being minimalistic and completely unopinionated regarding the developer’s choice of other frameworks and tools.

Other frameworks tend to fall into either too much abstraction (no-code, low-code, BaaS) or partial abstraction (MVC frameworks, GraphQL, ORMs, API generators, code generators), and tend to be opinionated regarding the development tool-chain, deployment environment, configuration/conventions or DSL. Remult attempts to strike a better balance.

Contributing

Contributions are welcome. See CONTRIBUTING.md.

  • 💬 Any feedback or suggestions? Start a discussion.
  • 💪 Want to help out? Look for "help wanted" labeled issues.
  • ⭐ Give this repo a star.

License

Remult is MIT Licensed.

remult's People

Contributors

aronpalffy avatar austinwhitbeck avatar bensos000 avatar burgalon avatar chipluxury-ewa avatar daan-vdv avatar dependabot[bot] avatar dmendezcreativ avatar ermincelikovic avatar eylonshm avatar gbuerk avatar gonergenesis avatar itamardavidyan avatar jycouet avatar khairul169 avatar kshired avatar maral avatar morfi11 avatar nevyen avatar noam-honig avatar oshriasulin avatar shavitohad avatar shmool avatar talmosko avatar vladdoster avatar yedidyar avatar yonarbel avatar yoni-rapoport 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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 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

remult's Issues

File uploading

Hello, any solution for file uploading and stream files via API?

Improve handling of multiple column ids

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

In the case of an entity that it's unique identifier is comprised by more than one column, today one needs to use the Compound id field:

@Entity<theTable>('', {
    id: t => new CompoundIdField(t.a, t.b)
})
class theTable extends EntityBase {
    @Fields.string()
    a: string;
    @Fields.string()
    b: string;
    @Fields.string()
    c: string;
}

Describe the solution you'd like
A clear and concise description of what you want to happen.

I think that the CompoundIdField is a complexity that can be avoided by allowing id to return more than one column - something like:

@Entity<theTable>('', {
    id: t => [t.a, t.b]
})
class theTable extends EntityBase {
    @Fields.string()
    a: string;
    @Fields.string()
    b: string;
    @Fields.string()
    c: string;
}

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

beforeClose to beforeClosed

Please change beforeClose to beforeClosed in radweb\projects\angular\src\angular\remult-core.module.ts line 78.

I'd also like to be able to potentially make pull requests for this project in the future.
But at the moment i get 403, not sure if this is normal or not.

Thanks

includeInApi doesn't work in nested objects

Describe the bug

When I write two entities, one nested inside the other, and I restrict a field on the nested entity with includeInApi, I still get the field when requesting the parent entity. It doesn't show when requesting the nested entity directly.

To Reproduce
Steps to reproduce the behavior:

  1. Create two entities, one nested in the other, with a restricted field in the parent. For example:
@Entity("products", {
  allowApiCrud: true
})
export class Product {
  @Fields.uuid()
  id!: string;

  @Fields.string()
  title = 'Product Title';

  @Fields.integer({includeInApi: false})
  stock = 0;
}

@Entity("orderItems", {
  allowApiCrud: true
})
export class OrderItem {
  @Fields.uuid()
  id!: string;

  @Field(() => Product)
  product!: Product;

  @Fields.integer()
  quantity = 0;
}
  1. Connect the entities to the API and add initial data:
export const api = remultExpress({
  entities: [OrderItem, Product],
  initApi: async remult => {
    const productRepo = remult.repo(Product);
    const product = await productRepo.insert({});

    const orderItemRepo = remult.repo(OrderItem);
    await orderItemRepo.insert({product});
  }
});
  1. Make a find() request (GET) on the orderItems repo.
  2. You'll see the product nested inside the orderItem, including its stock member.

Expected behavior
If the stock field is restricted, it shouldn't appear in the nested product when querying the orderItems.

Additional context
Tried this both with {includeInApi: false} and {includeInApi: "admin"} (with no actual admin user), same behavior.

When using CompoundIdColumn with Knex, get error on insert due to options being undefined - in method ("IsAutoIncrement")

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Error in sslInDev

When adding sslInDev: true in createPostgresConnection in api.ts,
I got an error: "The server does not support SSL connections"

2022-06-02_11h14_56

Add _null to documentation

I would like to see the use of _null added to the documentation.

Additional context
I found the IsNull and IsNotNull methods in FilterSerializer.ts. These are really handy. Documenting them here would be fantastic.

When using "virtual directory" the api calls sometimes fail

Describe the bug
A clear and concise description of what the bug is.

the default value of apiBaseUrl = '/api'; is problematic when using baseURL='/xx/index.html'
On the other hand, if it's set to api it fails if you have nested routes in the app. (ie '/customersPage/1')

We should find some solution for the default value of apiBaseUrl that will support both nested routes, and apps that reside in a virtual directory.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Add doc for using remult in custom backend code

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

Deploying to heroku problem

Hello guys, I have a problem with deploy to heroku, can't find postgres folder. Where should it be?

2022-07-22T13:38:22.815092+00:00 app[web.1]: > node dist/server/
2022-07-22T13:38:22.815093+00:00 app[web.1]: 
2022-07-22T13:38:22.973755+00:00 app[web.1]: node:internal/modules/cjs/loader:488
2022-07-22T13:38:22.973757+00:00 app[web.1]: throw e;
2022-07-22T13:38:22.973757+00:00 app[web.1]: ^
2022-07-22T13:38:22.973757+00:00 app[web.1]: 
2022-07-22T13:38:22.973758+00:00 app[web.1]: Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './postgres' is not defined by "exports" in /app/node_modules/remult/package.json
2022-07-22T13:38:22.973759+00:00 app[web.1]: at new NodeError (node:internal/errors:371:5)
2022-07-22T13:38:22.973759+00:00 app[web.1]: at throwExportsNotFound (node:internal/modules/esm/resolve:453:9)
2022-07-22T13:38:22.973760+00:00 app[web.1]: at packageExportsResolve (node:internal/modules/esm/resolve:731:3)
2022-07-22T13:38:22.973760+00:00 app[web.1]: at resolveExports (node:internal/modules/cjs/loader:482:36)
2022-07-22T13:38:22.973760+00:00 app[web.1]: at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
2022-07-22T13:38:22.973761+00:00 app[web.1]: at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
2022-07-22T13:38:22.973761+00:00 app[web.1]: at Function.Module._load (node:internal/modules/cjs/loader:778:27)
2022-07-22T13:38:22.973762+00:00 app[web.1]: at Module.require (node:internal/modules/cjs/loader:1005:19)
2022-07-22T13:38:22.973762+00:00 app[web.1]: at require (node:internal/modules/cjs/helpers:102:18)
2022-07-22T13:38:22.973762+00:00 app[web.1]: at Object.<anonymous> (/app/dist/server/api.js:9:20) {
2022-07-22T13:38:22.973763+00:00 app[web.1]: code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'
2022-07-22T13:38:22.973763+00:00 app[web.1]: }
2022-07-22T13:38:23.126667+00:00 heroku[web.1]: Process exited with status 1
2022-07-22T13:38:23.166298+00:00 heroku[web.1]: State changed from starting to crashed

In angular how can I handle error message in one way

I already set remult.apiClient.httpClient = http (angular HttpClient) in angular AppModule constructor
and I set an angular interceptor also
but in remult repo operation throw error, I can't get any error intercept message
just can do try catch get the error
I want easily to handle the error in one way
another idea?
thanks

Remult api data provider related

remove setDataProvider
remove _dataSource
Add get to SqlDatabase - that'll get the SqlDatabase
And for mongo
And for knex
etc...

Missing example and options doc for FindFirst

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Support Deno

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

When using websql and allow null, the table is created with not null

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Repository returns error on insert with mysql2 dataprovider and autoincrement id entity

Describe the bug
When trying to insert some data using mysql data provider and an entity with autoIncrement() data type, it will throw an error, but is successfully inserted into the database.

.returning() is not supported by mysql and will not have any effect.
Error: Undefined binding(s) detected when compiling WHERE. Undefined column(s): [id] query: where `id` = ?
    at QueryCompiler_MySQL.toSQL (D:\Projects\App\remult\remult-test\node_modules\knex\lib\query\querycompiler.js:110:13)
    at compileCallback (D:\Projects\App\remult\remult-test\node_modules\knex\lib\formatter\formatterUtils.js:13:19)
    at rawOrFn (D:\Projects\App\remult\remult-test\node_modules\knex\lib\formatter\wrappingFormatter.js:225:7)
    at QueryCompiler_MySQL.whereWrapped (D:\Projects\App\remult\remult-test\node_modules\knex\lib\query\querycompiler.js:1084:17)
    at QueryCompiler_MySQL.where (D:\Projects\App\remult\remult-test\node_modules\knex\lib\query\querycompiler.js:573:34)
    at D:\Projects\App\remult\remult-test\node_modules\knex\lib\query\querycompiler.js:133:40
    at Array.forEach (<anonymous>)
    at QueryCompiler_MySQL.select (D:\Projects\App\remult\remult-test\node_modules\knex\lib\query\querycompiler.js:132:16)
    at QueryCompiler_MySQL.toSQL (D:\Projects\App\remult\remult-test\node_modules\knex\lib\query\querycompiler.js:73:29)
    at Builder.toSQL (D:\Projects\App\remult\remult-test\node_modules\knex\lib\query\querybuilder.js:83:44)

To Reproduce
Steps to reproduce the behavior:

  1. Grab remult instance using mysql2 provider and get the repo
  2. Create entity with auto incremental id
import { Entity, Fields } from "remult";

@Entity("tasks")
export class Task {
  @Fields.autoIncrement()
  id!: number;

  @Fields.string()
  title = "";
}
  1. Insert some data
let task = await remult.repo(Task).insert({ title: "Test Task" });
console.log("CREATE", task);
  1. or clone and run this sample project: https://github.com/khairul169/remult-test-mysql

Expected behavior
Expected to return object of the task including its id

Screenshots
image

Desktop (please complete the following information):

  • OS: Windows 10 build 19043.1021
  • Browser: Chrome
  • Version: NodeJS v16.13.0

Additional context
Tested on postgres and jsonprovider, it works well.. only error with mysql2

Explain Active Record strategy in the docs

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

remult supports the ActiveRecord pattern, but most if not all of the docs do not reflect it.

Describe the solution you'd like
An article outlining the usage of ActiveRecord, pros and cons etc... would be useful

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

remult.isAllowed should also support @BackendMethod

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

In have a Backend method where it's allowed options determines who is allowed to run it:

@BackendMethod({ allowed: Allow.authenticated })

In the frontend, I would like to display the button only to users who can run the BackendMethod.
Today the only way I can do that, requires me to repeat myself and write:

remult.isAllowed(Allow.authenticated)

Describe the solution you'd like
A clear and concise description of what you want to happen.
I would prefer to have a single source of truth, meaning that if I defined the rule once in the backend method, I should be able to query it using something like:

remult.isAllowed(TasksController.setAll)

and that it'll take into consideration the allowed: AllowAuthenticated
Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

Add real time capabilities?

Discussed in #66

Originally posted by mariolorente May 24, 2022
It would be awesome if you can subscribe to any model/list. For me it would a no brainer to use this.

Scenarios that includes viewmodels.

First of all, I would like to thank you for this great library. Using multiple ViewModels for the same entity is a common scenario for web applications (Different validation sets for different operations, hiding and exposing some properties depending on the situations, etc.). I wonder how remult handles this kind of scenario. It would be nice if you can redirect me to a sample or documentation.

ErrorInfo interface refers also the methods and not only field.

Describe the bug
The ErrorInfo's modelState property includes references to the objects fields, but also to the object's methods.

To Reproduce
Consider the following class:

class person{
  firstName='';
  lastName='';
  getFullName(){
  return this.firstName+' '+this.lastName
  }
}

Expected behavior
A clear and concise description of what you expected to happen.
When I use the ErrorInfo type with it, it should only include firstName and lastName - and not - getFullName

Screenshots
If applicable, add screenshots to help explain your problem.
image
The getFullName shouldn't appear in the intelisense

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

When inserting several rows to json db using auto increment they are not inserted in the correct order

Describe the bug
A clear and concise description of what the bug is.

When I insert multiple rows using remult.repo().insert for an entity with an autoIncrement column - these rows are not inserted in the correct order.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error
@Entity('entityWithAutoId')
class entityWithAutoId extends EntityBase {
    @Fields.autoIncrement()
    id: number;
    @Fields.string()
    name: string;
}
...
        await remult.repo(entityWithAutoId).insert([
            { name: 'a' },
            { name: 'b' },
            { name: 'c' }
        ]);

Expected behavior
A clear and concise description of what you expected to happen.

  [          { id: 1, name: 'a' },
            { id: 2, name: 'b' },
            { id: 3, name: 'c' }]

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

GraphQL fails with "remult object was requested outside of a valid context"

The issue

I 've added GraphQL as in the docs (using a forked crm-demo) but GraphQL fails with "errors": [{ "message": "remult object was requested outside of a valid context, try running it within initApi or a remult request cycle",.... when requesting contacts.

To Reproduce

  1. Clone & checkout this branch https://github.com/anodynos/crm-demo/tree/poc/graphql && npm i

  2. The graphql code in copied from example to server/index.ts. I've also bypassed getUser: (req) => req.session!['user'], on server/api.ts and replaced it with static function returning the user, as that was crushing also with GraphQL

  3. Run and open http://localhost:3002/api/graphql

  4. Execute query { contacts { firstName } }

Expected behavior
Should return results, just like http://localhost:3002/api/contacts does or other entities on GraphQL.

Instead it returns this:

{
  "errors": [
    {
      "message": "remult object was requested outside of a valid context, try running it within initApi or a remult request cycle",
      "locations": [
        {
          "line": 33,
          "column": 7
        }
      ],
      "path": [
        "contacts"
      ]
    }
  ],
  "data": {
    "contacts": null
  }
}

Desktop (please complete the following information):

  • Ubuntu 22.04 / Node 16
  • Version 0.17

Join method between entities

Hello again, I have a tricky problem to solve. I have 2 entities (Services and Tiers), depends on docs I created them like below:

Services

import { Tier } from './/Tier';
import { Allow, Entity, Fields, IdEntity } from "remult";

@Entity("services", {
    allowApiRead: true,
    allowApiUpdate: Allow.authenticated,
    allowApiDelete: Allow.authenticated,
    allowApiInsert: Allow.authenticated,
})
export class Service {
    @Fields.uuid()
    id!: String;

    @Fields.string()
    title!: string;

    @Fields.string()
    description!: string;

    @Fields.string()
    image!: string;

    @Fields.number()
    price!: number;

    @Fields.object<Tier>((options, remult) => {
        options.serverExpression = async (tier) => {
            remult.repo(Tier).find({where: {serviceId: tier.id}});
        }
    })

    @Fields.boolean()
    active!: boolean;

    @Fields.boolean()
    featured!: boolean;
}

Tiers

import { Allow, Entity, Field, Fields, IdEntity } from "remult";

@Entity("tiers", {
    allowApiRead: true,
    allowApiUpdate: Allow.authenticated,
    allowApiDelete: Allow.authenticated,
    allowApiInsert: Allow.authenticated,
})
export class Tier extends IdEntity {
    @Fields.string()
    serviceId!: string;

    @Fields.string()
    name!: string;

    @Fields.number()
    price!: number;
}

Tiers are childs for Services, I'm using Angular and have no idea how to join them. Is there any solution for that? How can I appeal to Services via Tiers and vice versa?

remult Next.js Tutorial

Now i go to "Refactor from Front-end to Back-end" of Tutorial remult for Next.js at link:
https://remult.dev/tutorials/react-next/backend-methods.html#set-all-tasks-as-un-completed
when npm run dev: error is folow in console:

{
message: "can't use static remult in this environment, async_hooks were not initialized",
stack: [
"Error: can't use static remult in this environment, async_hooks were not initialized",
' at RemultAsyncLocalStorage.getRemult (/home/quangtynu/remult-nextjs-app/node_modules/remult/server/expressBridge.js:114:19)',
' at RemultProxy.remult_proxy_1.remult.remultFactory (/home/quangtynu/remult-nextjs-app/node_modules/remult/server/expressBridge.js:96:54)',
' at RemultProxy.repo (/home/quangtynu/remult-nextjs-app/node_modules/remult/src/remult-proxy.js:20:32)',
' at setAll (webpack-internal:///(api)/./src/shared/TasksController.ts:19:69)',
' at myServerAction.originalMethod (/home/quangtynu/remult-nextjs-app/node_modules/remult/src/server-action.js:197:114)',
' at myServerAction. (/home/quangtynu/remult-nextjs-app/node_modules/remult/src/server-action.js:146:71)',
' at step (/home/quangtynu/remult-nextjs-app/node_modules/tslib/tslib.js:144:27)',
' at Object.next (/home/quangtynu/remult-nextjs-app/node_modules/tslib/tslib.js:125:57)',
' at fulfilled (/home/quangtynu/remult-nextjs-app/node_modules/tslib/tslib.js:115:62)',
' at processTicksAndRejections (node:internal/process/task_queues:96:5)'
],
url: '/api/setAll',
method: 'POST'
}

I using Ubuntu on WSL2.
any idea about async_hooks?

Cannot use import statement outside a module

Describe the bug
I'm trying to use remult in my project. I'd like to use ES modules.

I get the following error:

(node:2822177) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/home/me/ts-app-esm-template/node_modules/remult/esm/remult-express.js:1
import * as express from 'express';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1033:15)
    at Module._compile (node:internal/modules/cjs/loader:1069:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Module._load (node:internal/modules/cjs/loader:827:12)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:170:29)
    at ModuleJob.run (node:internal/modules/esm/module_job:198:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:409:24)

Node.js v18.3.0

See GuillaumeDesforges/ts-app-esm-template#1

To Reproduce
Steps to reproduce the behavior:

WARNING requires node >= 18.x

  1. clone https://github.com/GuillaumeDesforges/ts-app-esm-template
  2. yarn install
  3. yarn build
  4. node api

Expected behavior
The import should not fail.

Json db doesn't respect `dbName` option on field

Describe the bug
The dbName option of a field, works great in postgres and sql - but doesn't work when it comes to json db.
To Reproduce
Consider the following class:

@Entity("tasks", {
    allowApiCrud: true
})
export class Task {
    @Fields.uuid()
    id!: string;

    @Fields.string({dbName:'theTitle')
    title = '';

    @Fields.boolean()
    completed = false;
}

When the data is stored in the tasks.json file, the second field is stored as title and not theTitle

[
  {
    "id":"a",
    "title":"Task a"
  }
]

Expected behavior
it should be called theTitle in the json file:

[
  {
    "id":"a",
    "theTitle":"Task a"
  }
]

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

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.