marmelab / aor-graphql Goto Github PK
View Code? Open in Web Editor NEWPackages related to using GraphQL with Admin-on-rest
Packages related to using GraphQL with Admin-on-rest
Hello, how should I use this ReferenceManyField ? I tried something like:
<ReferenceManyField label="Grupos" reference="Group" target="users">
but I got:
GraphQL error: Variable '$filter' expected value of type 'GroupFilter' but got: {"users":{"id":"cja7m71tyoen201503owjey8g"}}. Reason: 'users' Field 'users' is not defined in the input type 'GroupFilter'
thanks
There's a little bug on the admin-on-rest-graphql-demo.
On the Posters List I get a graphql error when I try to search or use any other filter than the category.
GraphQL error: Variable '$filter' expected value of type 'ProductFilter' but got: {"q":"d"}. Reason: 'q' Field 'q' is not defined in the input type 'ProductFilter'. (line 1, column 19): query allProducts($filter: ProductFilter, $orderBy: ProductOrderBy, $last: Int) {
It seems like this line of code is causing the introspection resolver to always return an an empty array for resources
.
Should this check be an ||
operator instead of an &&
operator?
The returned operation names for the GET_LIST
and GET_ONE
fetch types are never going to be the same so it doesn't make sense for these 2 conditions to be both true at the same time.
We're having a strange issue with loading certain nodes from our schema.
We've scaffolded up AoR and got authentication working, as well as basic listing of nodes.
I'm going to paste our schema below (long, sorry...). Everything 'works' (meaning AoR can list records of that node) EXCEPT:
These three return 'GraphQL Error: Insufficient Permissions` with a number of repetitions in the console.
All Graphcool permissions are wide open (no restrictions on fields or relationships). All nodes have data in them.
Looking for some guidance on how to troubleshoot this issue - we can't figure out the commonalities between these nodes.
Really appreciate any pointers.
type File implements Node {
contentType: String!
createdAt: DateTime!
id: ID! @isUnique
name: String!
secret: String! @isUnique
size: Int!
updatedAt: DateTime!
url: String! @isUnique
userAvatar: User @relation(name: "UserAvatar")
bannerImageFile: Job @relation(name: "BannerImageFile")
logoImageFile: Job @relation(name: "LogoImageFile")
}
type Job implements Node {
createdAt: DateTime!
id: ID! @isUnique
title: String!
updatedAt: DateTime!
user: User! @relation(name: "JobOnUser")
category: JobCategories @defaultValue(value: None)
duration: JobDurations @defaultValue(value: Full_Time)
jobBody: String
jobBodyJson: Json
slug: String @isUnique
slugAtLastEdit: String
isPublished: Boolean! @defaultValue(value: false)
datePublished: DateTime
products: [Product!]! @relation(name: "ProductsOnJob")
bannerImageFile: File @relation(name: "BannerImageFile")
logoImageFile: File @relation(name: "LogoImageFile")
institution: String
salary: String
applicationUrl: String
country: String
region: String
city: String
}
type Product implements Node {
id: ID! @isUnique
priceBase: Int
pricePaid: Int @defaultValue(value: 0)
job: Job @relation(name: "ProductsOnJob")
publishDate: DateTime
expiryDate: DateTime
createdAt: DateTime!
inCart: Boolean! @defaultValue(value: false)
credit: Credit @relation(name: "CreditOnProduct")
type: ProductType @relation(name: "TypeOnProduct")
updatedAt: DateTime!
disableOverride: Boolean! @defaultValue(value: false)
charge: Charge @relation(name: "ProductsOnCharge")
children: [Product!]! @relation(name: "ProductOnProduct")
parent: Product @relation(name: "ProductOnProduct")
}
type ProductType implements Node {
id: ID! @isUnique
name: String
price: Int!
createdAt: DateTime!
updatedAt: DateTime!
products: [Product!]! @relation(name: "TypeOnProduct")
credits: [Credit!]! @relation(name: "TypeOnCredit")
}
type Credit implements Node {
id: ID! @isUnique
type: ProductType @relation(name: "TypeOnCredit")
user: User @relation(name: "CreditOnUser")
createdAt: DateTime!
updatedAt: DateTime!
used: Boolean
applied: Boolean
product: Product @relation(name: "CreditOnProduct")
}
type CouponCode implements Node {
id: ID! @isUnique
createdAt: DateTime!
updatedAt: DateTime!
code: String!
percentReduction: Int
priceReduction: Int
useCount: Int
description: String
validFrom: DateTime
validTo: DateTime
appliedTo: [Charge!]! @relation(name: "CouponOnCharge")
}
type Charge implements Node {
id: ID! @isUnique
stripeToken: String
stripeCharge: Json
stripeChargeId: String
stripeChargeError: String
createdAt: DateTime!
updatedAt: DateTime!
products: [Product!]! @relation(name: "ProductsOnCharge")
coupon: CouponCode @relation(name: "CouponOnCharge")
paymentType: PaymentTypes
checkedOut: Boolean! @defaultValue(value: false)
paid: Boolean! @defaultValue(value: false)
totalPrice: Int! @defaultValue(value: 0)
user: User @relation(name: "ChargesOnUser")
dummy: Boolean! @defaultValue(value: true)
}
type User implements Node {
role: Roles! @defaultValue(value: Employer)
createdAt: DateTime!
id: ID! @isUnique
email: String @isUnique
password: String
jobs: [Job!]! @relation(name: "JobOnUser")
credits: [Credit!]! @relation(name: "CreditOnUser")
updatedAt: DateTime!
userAvatar: File @relation(name: "UserAvatar")
firstName: String
lastName: String
phoneNumber: String
userJobTitle: String
institutionName: String
institutionAddress: String
institutionCity: String
institutionPostal: String
institutionProvince: String
institutionCountry: String
resetToken: String @isUnique
resetExpires: DateTime
passwordReset: Boolean! @defaultValue(value: false)
sendWelcomeEmail: Boolean! @defaultValue(value: false)
dateWelcomeEmailSent: DateTime
legacyUserData: Json
legacyUser: Boolean @defaultValue(value: false)
charges: [Charge!]! @relation(name: "ChargesOnUser")
invoiceApproved: Boolean @defaultValue(value: false)
}
/User
For the first time, it will show "No results found"
/User/create
After I successfully create an user, and head back to /User
, it still show "No results found".
Clicking on Refresh
button has no effect. Have to do a full reload.
I even created a new record (User) manually in the graphcool backend, when going back and forth between routes, the new record does not show up in /User
. But it works fine with update!
Am I doing something wrong? This is the case in two of my apps, please help!
We should be able to add arbitrary headers
The basket is now stored in its own resource.
Thus, we need a ReferenceFields
component.
I want to make a request to graph.cool like this.
{
name: "client name",
address: "place",
contacts: [{
email: "email",
Phone: "234"
}]
},
These are my components.
export const ClientCreate = (props) => (
<Create title="Create a Client" {...props}>
<SimpleForm>
<TextInput source="name" />
<TextInput source="address" options={{ multiLine: true }} />
<Contacts addField source="contacts" />
</SimpleForm>
</Create>
);
class Contacts extends Component {
constructor(props) {
super();
console.log(props)
this.state = {
contacts: [{ email: "", phone: "" }]
};
}
handleChange = (event, index, value) => {
const name = event.target.name;
const contacts = this.state.contacts;
const updatedContact = { ...value, [name]: event.target.value };
contacts[index] = updatedContact;
this.setState({ contacts: contacts });
this.props.input.onChange(contacts);
}
handleSubmit = (event) => {
const count = [...this.state.contacts, { email: "", phone: "" }];
this.setState({ contacts: count });
}
newComponents() {
// const componentsArray = [...Array(this.state.count).keys()];
return this.state.contacts.map((value, index) => {
return <div>
<h3>Contact-{index + 1}</h3>
<TextInputField placeholder="Email" name="email" value={value.email} onChange={(e) => { this.handleChange(e, index, value) }} />
<TextInputField placeholder="Phone" name="phone" value={value.phone} onChange={(e) => { this.handleChange(e, index, value) }} />
</div>
});
}
render() {
return <div>
<h3>{this.state.count}</h3>
{this.newComponents()}
<input type="button" value="Add" onClick={this.handleSubmit} />
</div>
}
}
This is being converted contactsIds
Because of this source in this repo
Is there a way to allow the nested mutation without Ids?
I'm trying to do signIn
via graphCool
, but in authClient.js
I have to access the restClient
that is created by aor-graphql
.
One way is to export the client and import it in authClient.js, which I think is not possible as the client creation seems to be asynchronous. Another way is to use fetch
.
Wondering what would be the preferred way?
Is there any way to clone the graphcool schema and demo data to use the demo with your own endpoint?
Hi, thanks for this great combination (admin-page on reactjs, material-ui, apollo, graphql). Now, I'm looking to access the latest Apollo-2 cut so I don't re-invent. Precisely which branches should I fetch?
There are two options for this:
Wanted to try sorting a Resource by a specific field, and the sort order always seemed off - correct within the page of results, but not correct across multiple pages.
Let's say I have 30 results, displaying 10 per page, and I sort them ascending, by their IDs. I'd expect the following:
Page 1: IDs 0-9
Page 2: IDs 10-19
Page 3: IDs 20-29
Instead, I see the following:
Page 1: IDs 20-29
Page 2: IDs 10-19
Page 3: IDs 0-9
In buildVariables.js
around line 80, the parameters skip
, last
and orderBy
seem relevant. I logged them out, and here's how they relate to the above weirdly ordered pages:
Page 1: IDs 20-29 - skip: 0, last: 10
Page 2: IDs 10-19 - skip: 10, last: 10
Page 3: IDs 0-9 - skip: 20, last: 10
It seems the effect these parameters seem to have is:
orderBy
- first the elements are ordered as requested, in this case, 0-29
skip
- next, the first skip
# of elements are removed. if last
is set, they seem to be removed from the end of the ordered elements, if first
is set, they're removed from the start.
last
- finally, the last last
# of elements are returned.
In short, in the return of the function buildGetListVariables
in buildVariables.js
, by just changing
last: parseInt(params.pagination.perPage),
to
first: parseInt(params.pagination.perPage),
the problem seems to be solved.
Let me know if that makes any sense! I can't seem to find any documentation on skip
...
NOTE
After getting this working at least for my use case, I realized that the aor-graphql-client-graphcool package on npm that I'm using points to a repo that's old and gone. So I wasn't sure where I should post this - but it seems to apply to this repo as well!
Heya!
I'm trying to set up admin-on-rest with a graph.cool instance, with the npm package aor-graphql-client-graphcool
, but updating Booleans to false and other fields to falsy values doesn't work - instead, those values are excluded from the query.
I think this is because variables are being filtered out in buildGqlQuery.js
, where the variable validVariables
is created.
(similar filtering happens in two other places in
queryBuilder.js
, but I think the way I have AoR setup means those instances don't seem to get used)
I'm not sure if this fix works in every case, but in the functions buildArgs
and buildApolloArgs
in buildGqlQuery.js
, I've just replaced the below:
const validVariables = Object.keys(variables).filter(k => !!variables[k] && variables[k] !== null);
with:
const validVariables = Object.keys(variables).filter(k => typeof variables[k] !== 'undefined' && variables[k] !== null);
(in the npm package it's not quite the same hotshot arrow syntax, but close enough!)
I've an User
model that belongs to a Site
model. If the User record has siteId
, there is no problem in listing them in admin on rest
app. When there is a new User
record with a null
value in siteId
field, in the admin on rest app, I get an error Cannot read property id of null
.
Is there a way to allow the records with null relations as well? (When the relation is one-one, it is difficult to always the child record value)
As the README rightly says, I face this issue. How do I fix this, please help? Thanks in advance 👍
When I create or edit a resource, the list or edit page does not refresh its data
admin-on-rest maintain its own cache of resources data but, by default, so does the Apollo client. For every queries, we inject a default fetchPolicy set to network-only so that the Apollo client always refetch the data when requested.
Do not override this fetchPolicy.
Currently, while the filter itself work, when refreshing the page it is not populated from url.
Hi, I've been searching for a way to manage our content through our own GraphQL API and this repo came up in the search, ça a l'air super !
Would you have instructions on how to adapt the code to plug into a remote Prisma endpoint? I'm a bit confused because on the one hand there seems to be some introspection code (e.g in aor-graphql-client/src/index.js
, but on the other hand in the demo the stuff seems to be hard-coded (e.g there are custom React components admin-on-rest-graphql-demo/src/dashboard/PendingOrders.js
etc). Do you have any up to date "getting started" documentation? Thanks a lot
NB: I found this older post, but it seems it is not applicable any more.
Im trying to implement authentication and are having some problems. Im using the AOR auth guide as reference https://github.com/marmelab/admin-on-rest/blob/master/docs/Authentication.md
Do I let express middleware handle auth or can I use graphql directly?
Does anyone have a working auth sample?
Thanks!
TypeError: queryBuilderFactory is not a function
Is thrown whenever buildApolloClient() is passed any options.
Would it be possible to create an option to reference a local schema.graphql
or schema.json
file to be used for introspection, instead of running a introspection query?
The ability to pass a schema to the buildApolloClient
which I retrieved beforehand with for example get-graphql-schema, would be very helpful as my schema doesn't change much.
If I'm not mistaken, it could significantly reduce the initial loading time and perhaps there would no longer be a need for Admin
to wait for restClient
to be loaded.
I'm really looking forward to this project! However I see this - "This is very WIP. It currently requires changes on admin-on-rest which have not been published yet."
I was wondering what the plans are for this to be ready to use in production. Also, does upcoming AOR 2.0.0 release the changes published for graphql to work seamlessly?
Thank you for this awesome library. I'm wondering where I'm going wrong in integrating this library into my fresh admin-on-rest
app.
Failed to compile.
./~/aor-graphql-client-graphcool/lib/index.js
Module not found: Can't resolve 'aor-graphql-client' in '/home/vysakh/aor-cool/node_modules/aor-graphql-client-graphcool/lib'
So I included "aor-graphql-client": "^0.0.1-0"
and got a different error,
×
Unhandled Rejection (Invariant Violation): addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner).
▶ 29 stack frames were collapsed.
(anonymous function)
src/App.js:17
14 | .then((res) => {
15 | console.log('set restClient');
16 | console.log(res)
> 17 | this.setState({restClient: res})
18 | });
19 | }
20 |
// package.json
{
"name": "aor-cool",
"version": "0.1.0",
"private": true,
"dependencies": {
"admin-on-rest": "^1.2.1",
"aor-graphql-client": "^0.0.1-0",
"aor-graphql-client-graphcool": "^0.0.1-0",
"apollo-client": "^1.9.0-0",
"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-scripts": "1.0.10"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
// App.js
import React, { Component } from 'react';
import { Admin, Resource } from 'admin-on-rest';
import buildApolloClient from 'aor-graphql-client-graphcool';
import PostIcon from 'material-ui/svg-icons/action/book';
import { PostList, PostEdit, PostCreate } from './pages/posts';
class App extends Component {
constructor() {
super();
this.state = { restClient: null };
}
componentDidMount() {
buildApolloClient({ client: { uri: 'https://api.graph.cool/simple/v1/key' }})
.then((res) => {
console.log('set restClient');
console.log(res)
this.setState({restClient: res})
});
}
render() {
const { restClient } = this.state;
console.log('restClient', restClient);
if (!restClient) {
return <div>Loading</div>;
}
return (
<Admin restClient={restClient}>
<Resource
icon={PostIcon}
name="Post"
list={PostList}
edit={PostEdit}
create={PostCreate}
/>
</Admin>
);
}
}
export default App;
Which client is best suited to a standard GraphQL setup using only GraphQL-JS on the backend? I would assume aor-graphql-client
, as aor-graphql-client-simple
seems to no longer exist. However the docs say this should not be used directly... in cases where graphcool is not being used are we required to create our own client with aor-graphql-client
?
This is a very low level library which is not meant to be used directly unless you really want full control or are building a custom GraphQL client.
It provides the foundations for other packages such as:
aor-graphql-client-simple
aor-graphql-client-graphcool
I'm exploring the AoR ecosystem and am finding myself confused by all the different packages/repos. Specifically I'm wondering about the graphql (I'm using Graphcool) integration.
This isn't meant as a whiny question, so please don't take it that way. I get that you guys are exploring all kinds of directions, and also, you know...working :)
Thanks for making this, and all the contributions you do.
Here's my App.js file, I don't see any changes in the theme.
import 'babel-polyfill';
import React, { Component } from 'react';
import { Admin, Delete, Resource } from 'admin-on-rest';
import buildApolloClient from './aorApolloClient';
import './App.css';
import authClient from './authClient';
import sagas from './sagas';
import themeReducer from './themeReducer';
import Login from './Login';
import Layout from './Layout';
import Menu from './Menu';
import { Dashboard } from './dashboard';
import customRoutes from './routes';
import translations from './i18n';
import { VisitorList, VisitorEdit, VisitorDelete, VisitorIcon } from './visitors';
import { CommandList, CommandEdit, CommandIcon } from './commands';
import { ProductList, ProductCreate, ProductEdit, ProductIcon } from './products';
import { CategoryList, CategoryEdit, CategoryIcon } from './categories';
import { SegmentList, SegmentIcon } from './segments';
import { ReviewList, ReviewEdit, ReviewIcon } from './reviews';
import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import {
blue400, blue700,
pinkA200,
grey100, grey300, grey400, grey500,
white, darkBlack, fullBlack,
} from 'material-ui/styles/colors';
import { fade } from 'material-ui/utils/colorManipulator';
import spacing from 'material-ui/styles/spacing';
const myTheme = {
spacing: spacing,
fontFamily: 'Roboto, sans-serif',
palette: {
primary1Color: blue400,
primary2Color: blue700,
primary3Color: grey400,
accent1Color: pinkA200,
accent2Color: grey100,
accent3Color: grey500,
textColor: darkBlack,
alternateTextColor: white,
canvasColor: white,
borderColor: grey300,
disabledColor: fade(darkBlack, 0.3),
pickerHeaderColor: blue400,
clockCircleColor: fade(darkBlack, 0.07),
shadowColor: fullBlack,
},
}
class App extends Component {
constructor() {
super();
this.state = { restClient: null };
}
componentWillMount() {
buildApolloClient()
.then(restClient => this.setState({ restClient }));
}
render() {
if (!this.state.restClient) {
return <div>Loading</div>;
}
return (
<Admin
title="Cruceritis HQ"
restClient={this.state.restClient}
customReducers={{ theme: themeReducer }}
theme={getMuiTheme(myTheme)}
customSagas={sagas}
customRoutes={customRoutes}
authClient={authClient}
dashboard={Dashboard}
loginPage={Login}
appLayout={Layout}
menu={Menu}
messages={translations}
locale="es"
>
<Resource name="Customer" list={VisitorList} edit={VisitorEdit} remove={VisitorDelete} icon={VisitorIcon} />
<Resource name="Command" list={CommandList} edit={CommandEdit} remove={Delete} icon={CommandIcon} options={{ label: 'Orders' }} />
<Resource name="Product" list={ProductList} create={ProductCreate} edit={ProductEdit} remove={Delete} icon={ProductIcon} />
<Resource name="Category" list={CategoryList} edit={CategoryEdit} remove={Delete} icon={CategoryIcon} />
<Resource name="Review" list={ReviewList} edit={ReviewEdit} icon={ReviewIcon} />
<Resource name="Segment" list={SegmentList} icon={SegmentIcon} />
<Resource name="CommandItem" />
</Admin>
);
}
}
export default App;
I'm clueless at what I might be doing wrong...
This would require to export a custom Admin
component which would decorate the aor one.
It would parse the children checking which resources are handled manually (declared with Resource
components) and add automatically generated ones for the others.
I had a quick question as to why this project doesn't support/use npm test/ npm start etc etc or even yarn? It is most likely that I have done something wrong as I am not used to make.
The reason I ask is because when I go into the aor-graphql folder and run make install, I get the following error:
$ make install
make i info Invoking install target
(node:30136) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): undefined
(node:30136) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
make × ERR not found: make-##
However, make help
runs "fine"
Hi, nice work! When I tried integrate these packages I couldn't find them on NPM. Is it possible to publish them or are there reasons for not doing so?
I'm using the latest master branch, trying to pass a custom apollo client as per the docs.
buildApolloClient({ client: new ApolloClient(...) });
However the client seems to be getting overwritten. Taking a closer look it seems to be happening at this line: https://github.com/marmelab/aor-graphql/blob/master/packages/aor-graphql-client/src/index.js#L46
Should this be using an OR operator instead? Otherwise it always continues to build a new client. Or am I missing something?
const client = clientObject || buildApolloClient(clientOptions);
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.