codeledge / ra-data-simple-prisma Goto Github PK
View Code? Open in Web Editor NEWPrisma tools and Data Adapter for React Admin
Prisma tools and Data Adapter for React Admin
This type expects a top-level filter
as well as a filter
in the params. React Admin only sends the filter in params like:
{
method: 'getList',
resource: 'posts',
params: {
pagination: {
page: 1,
perPage: 10
},
sort: {
field: 'id',
order: 'ASC'
},
filter: {}
}
}
The top-level filter
property should be removed so type checks work properly.
await options?.transform?.(data);
=> mappedData = await options?.mapData.(data);
currently the default handler has a type conflict with
new PrismaClient({}).$extends({
Hi,
I started working with ra-data-simple-prisma a time ago, it's very cool solution, thank you a lot!
I found an issue with the filter (where), as I been saw, It's is no posible to search for more than 1 column on each text input,
I find a solution, I would love to shere with you, would be great to know what do you think :)
passing a string with separate ',' for each column and ':' for the related fields
const profileFilters = [
<TextInput key="1" label="Smart Search" source="firstName,lastName,idNumber,user:email" alwaysOn resettable={true}/>
];
const userFilters = [
<TextInput key="1" label="Smart Search" source="name,email,companies:some:name" alwaysOn />,
];
in the extractWhere.ts
if (colName.includes(",") || colName.includes(":")) {
const colsName = colName.split(",");
auxWhere = colsName.map((colName, i) => {
const aux = {}
setObjectProp(aux, colName.replaceAll(':','.'), {
contains: value,
mode: options?.filterMode ? options?.filterMode : "insensitive",
});
return {...aux}
});
setObjectProp(where, 'OR', auxWhere)
return;
}
MongoDB has support for array fields, but the defaultHandler presumes an array value is only used for updating foreign key relationships. I would just recommend doing something like this for the array case:
if (foreignConnectKey) {
...existing code...
} else {
fields[key] = value;
}
Sorry for posting as an issue, i wasnt sure where else to post this.
I struggled to get this data provider working with the NextJS App Router approach. I now have it working and so i thought i'd share the code in case you want to add it to your readme.
In short, i had to create a folder and file at app/api/[resource]/route.ts
And then in route.ts, i added:
`// /api/[resource]/route.ts <= catch all resource requests
import { defaultHandler } from "ra-data-simple-prisma";
import { NextResponse } from "next/server";
import prisma from "@/utils/db";
// POST request
export async function POST(req: Request) {
let reqCloned = req.clone();
const body = await req.json();
let res = await defaultHandler({ body }, reqCloned, prisma);
return NextResponse.json(res);
}`
I wanted to use _id
field as id, so I wrote this. (I also had to remove "id" from orderBy tbh.)
import { defaultHandler, getListHandler } from 'ra-data-simple-prisma';
import { NextApiRequest, NextApiResponse } from 'next';
import { PrismaClient } from '@prisma/client';
import { retrieveDatabaseUrl } from '../../src/logic/retrieveDatabaseUrl';
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (!process.env['DATABASE_URL']) {
process.env['DATABASE_URL'] = await retrieveDatabaseUrl();
}
const prismaClient = new PrismaClient();
switch (req.body.method) {
case 'getList':
return getListHandler(req, res, prismaClient.user, {
transform: (data: Array<any>) => {
return data.map((entry) => ({
...entry,
id: Object.entries(entry).find(([key]) => key === '_id')?.[1],
}));
},
});
default:
return defaultHandler(req, res, prismaClient);
}
};
export default handler;
However, this gives me an error,
The response to 'getList' must be like { data : [{ id: 123, ...}, ...] }, but the received data items do not have an 'id' key. The dataProvider is probably wrong for 'getList'
.
Is transform working as intended?
Or should I use something other than transform?
React admin uses the q
field to implement a full-text search in the database, my suggestion is to use something like the prisma full-text search preview feature to implement the dynamic full text searching inside of the projects
You say that this can work with any node-based backend. However, it seems the whole implementation is based on next.js request handlers. Could you please provide an example for remix? Thanks!
Hi, thank you for this project ๐๐ผ.
I would like to pass httpOnly cookies on every subsequent requests. With Axios, it seems that it is possible with the axios.create()
method, like so:
const instance = axios.create({
withCredentials: true,
baseURL: BASE_URL
})
However, in your package it seems unreachable:
Any solution ?
I'd like to have the option to use the include
property for Prisma's findMany
call that is used by the getMany
and getManyReference
API handlers. Both of these handlers should support the same set of options that are supported for the getList
API handler.
Hi
Thank you for your work! I just want to report that I added CloneButton component in the List DataGrid and got following error while trying to copy record:
/app/node_modules/ra-data-simple-prisma/dist/index.js:606:27
603 const where = { id };
604 if (options == null ? void 0 : options.debug)
605 console.log("getOneHandler:where", where);
606 const row = await model.findUnique({
where: {
id: 'create'
~~~~~~~~
},
select: undefined,
include: undefined
})
Argument id: Got invalid value 'create' on prisma.findUniquePage. Provided String, expected Int.
to clarify #46
The following code, written as per the README, throws an error when executed.
<Admin dataProvider={
dataProvider("/api")
}>
The cause is the following code:
Replacing the cause with the following code will no longer throw an error:
{
headers: options.headers,
}
Or use the following code:
<Admin dataProvider={
dataProvider("/api", {})
}>
I think documentation needs improvement, i found out today that i can map my implicit many2many in handlers, not on client, so i think i can help add docs and share my handler improvements with l use in production like createMany support or create/createOrConnect typings and support
React Admin describes how to handle errors in https://marmelab.com/react-admin/DataProviderWriting.html#error-format
There is an existing error class defined in React Admin specifically for this called HttpError
. In this adapter, the error handler is throwing strings rather than error objects with a status field. It should be updated to throw instances of HttpError.
Whenever I try to create a new record, I get a "Element does not exist" error toast (a xhr post call returns {data: null}
.
Did I miss something?
I'd like to pass through the include
object to identify relational properties to include, but there isn't a getOne
options key for defaultHandler
.
Also, the 'create' and 'update' method handlers should also support Prisma's include
option, to allow propagating relational properties.
A lot of the methods does this kind of operation to the body params id,
where: { id: +req.body.params.id }
This will result in NaN
when the id being sent is type of string. Making it doesn't support string datatypes of id. And a simple change could be done like this,
diff --git a/node_modules/ra-data-simple-prisma/dist/index.js b/node_modules/ra-data-simple-prisma/dist/index.js
index b3dbbe5..0372eec 100644
--- a/node_modules/ra-data-simple-prisma/dist/index.js
+++ b/node_modules/ra-data-simple-prisma/dist/index.js
@@ -285,7 +285,7 @@ var getManyHandler = async (req, res, table) => {
var getOneHandler = async (req, res, table, options) => {
var _a, _b, _c;
const row = await table.findUnique({
- where: { id: +req.body.params.id },
+ where: { id: /^\d+$/.test(req.body.params.id) ? +req.body.params.id : req.body.params.id },
select: (_a = options == null ? void 0 : options.select) != null ? _a : void 0,
include: (_b = options == null ? void 0 : options.include) != null ? _b : void 0
});
@@ -305,7 +305,7 @@ var updateHandler = async (req, res, table, options) => {
return fields;
}, {});
const updated = await table.update({
- where: { id: +req.body.params.id },
+ where: { id: /^\d+$/.test(req.body.params.id) ? +req.body.params.id : req.body.params.id },
data
});
return res.json({ data: updated });
@@ -314,12 +314,12 @@ var updateHandler = async (req, res, table, options) => {
// src/deleteHandler.ts
var deleteHandler = async (req, res, table, options) => {
const deleted = (options == null ? void 0 : options.softDeleteField) ? await table.update({
- where: { id: +req.body.params.id },
+ where: { id: /^\d+$/.test(req.body.params.id) ? +req.body.params.id : req.body.params.id },
data: {
[options == null ? void 0 : options.softDeleteField]: new Date()
}
}) : await table.delete({
- where: { id: +req.body.params.id }
+ where: { id: /^\d+$/.test(req.body.params.id) ? +req.body.params.id : req.body.params.id }
});
return res.json({ data: deleted });
};
Edit : Add RegEx test if a string is a number
Hi!
First thank you very much for your work!
I got some issue connecting some elements to another one in an implicit many to many relationship :
I can't understand the comment on lince 70 in updateHandler.js file :
// transform an array to a connect (many-to-many)
Because just after that you put a "set" with the following code :
fields[key] = { set: (value as number[]).map((value) => ({ [foreignSet]: value, })), };
which is making my prisma update call failing. It works perfectly locally replacing "set" by "connect".
Am I missing some point or it is a mistake on your side ? I precise that I am on version 2.3.2 (latest at write time)
Thank you.
Have a nice day!
Brian
I'm using Prisma with MongoDB and my property names referencing external collections look like this: childId
or parentId
.
When I try to apply a filter in React Admin that selects for parentId="mongo-db-id-string"
, I get an error, because the API handler translates the filter into a where clause like this:
{
"parentId": {
"contains": "mongo-db-id-string",
"mode": "insensitive"
}
}
This causes an exception in the Prisma client, since it doesn't consider parentId
a string property, but an ID property that doesn't support contains
. I found the place in the API handler that applies this handling for string properties. Ideally, I would like a way to control whether such a fuzzy match is applied. Sometimes I want to select for a specific exact string match, and wouldn't want either an insensitive search OR a "contains" type of search to be used. But, in this case, simply including a test for the column name ending with Id
should suffice and would be easy to apply.
as per #46 (comment)
Currently I'm developing apps that require one of the field to be the type of JSON. (Prisma Reference)
The problem is every time the data is updated to the database, the JSON field would not be updated. I've done some digging and found this code at the file updateHandler.ts
.
if (!isObject(value) && !options?.skipFields?.includes(key))
fields[key] = value;
return fields;
I think the problem is, that this library thinks the JSON field is actually a relation to another model, so it is skipped. I think there should be a way to differentiate it, or at least have a configuration to allow a particular field on a model to be updated.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.