serving images with graphql - graphql

I have graphql server built by express-graphql and I use mongoDb to store images in normal database collection since they are < 16MB.
I have react and android app. What is the best way to serve these images to the clients.
In my schema I have something like this.
const productSchema = new Schema({
views: {type: Number, default: 0},
//Storing only thumbnail in this document.
thumbnail: {data: Buffer, contentType: String},
});
And in my schema I have something like
const productType = new GraphQLObjectType({
name: 'Product',
fields: () => ({
//.........
thumbnail: {type: 'WHAT TO DO HERE'},
views: {type: new GraphQLNonNull(GraphQLInt)}
//.........
}),
});
Edit:
I created a router like this.
router.get('/t/:productId', function (req, res) {
const productId = req.params.productId;
Product.findById(productId, {thumbnail: true}).then(thumbnail => {
res.contentType(thumbnail.contentType);
res.end(thumbnail.data, "binary");
}).catch(e => {
console.error(e);
res.sendStatus(404);
});
});

GraphQL.js responses are serialized as JSON, which means you can't serve images with it. You can return either a URL or a Base64-encoded string representing the image, as described in this answer. Either way the type for your field would be GraphQLString.

Related

using rtk query, how to pull this data from another view

I am trying to understand functionality with Redux toolkit and RTK Query.
I have a functioning query in one view. My question is how do I pull this information in another view?
this is how I launch the query in view #1
const Sidebar = () => {
const { data: clients = [], isFetching: clientsFetching } =
useGetClientsQuery("x#x.com");
this is my single api slice object
//define our single api slice object
export const tradesApi = createApi({
//the cache reducer expects to be added at 'state.api' (already default - this is optional)
reducerPath: "tradesApi",
//all of our requests will have urls starting with '/fakeApi'
baseQuery: fetchBaseQuery({ baseUrl: "https://localhost:44304/api/" }),
//the 'endpoints' represent operations and requests for this server
endpoints: (builder) => ({
//the 'getposts' endpoint is a "query" operation that returns data
getClients: builder.query<ClientData[], string>({
query: (username) => `/dashboard/returnClients?username=${username}`,
}),
getTradeDetail: builder.query<TradeData, number>({
query: (id) => `/dashboard/returnTest?id=${id}`,
}),
}),
});
export const { useGetTradesQuery, useGetClientsQuery, useGetTradeDetailQuery } =
tradesApi;
when I am in view #2, how do I pull this information without querying the api again? I simply want to grab it from the store.
thank you!
You just call useGetClientsQuery("x#x.com"); in the other component. It won't make another request, but just pull the data from the store.

Apollo readQuery, get data from cache

I'm trying to get data from Apollo cache. I know that data is there because in Apollo dev tools specified records are available.
In my react app I making a simple click and set Id which later passes to the query. Result from client.readQuery(...) is null. I'm spinning around because don't know why. I'm using code exactly the same way as in docs.
Here's a QUERY:
export const RECRUIT_QUERY = gql`
query Recruit($id: ID!) {
Recruit(_id: $id) {
_id
firstName
}
}
`;
Usage of apollo hooks in component:
const client = useApolloClient();
const recruit = client.readQuery({
query: RECRUIT_QUERY,
variables: { id: selectedId }
})
Configuration of apollo:
export const client = new ApolloClient({
link: concat(
authMiddleware,
new HttpLink({
uri: process.env.REACT_APP_API_URL,
}),
),
cache: new InMemoryCache(),
});
Here's apollo store preview:
Using readFragment covers my expectation. previously I have tried this solution but wrongly, ex:
client.readFragment({
id: '4587d3c2-b3e7-4ade-8736-709dc69ad31b',
fragment: RECRUIT_FRAGMENT,
});
In fact Appollo store cound't find this record. Correct solution looks like this:
client.readFragment({
id: 'Recruit:4587d3c2-b3e7-4ade-8736-709dc69ad31b',
fragment: RECRUIT_FRAGMENT,
})

Elegant and efficient way to resolve related data in GraphQL

What can be the best way to resolve the data in GraphQL
Here i have a SeekerType and JobType, JobsType is nested in SeekerType
A Seeker can apply to many Jobs. When Querying for a seeker, One can just query for seeker's data or as well as he can query for nested JobType and can get the jobstype data too.
But the Question is that If One doesn't Query for nested JobType
he won't get the Jobs data but mine Seeker resolver in viewerType would be fetching that data too.
So, while providing data to the seeker query how can i handle that, Either he can only want seeker details or may want the jobs details too.
Shall I use resolver of each nestedType and get the parent object, and fetch the relevant data using fields from parent Object???
The code below is just for illustration and clarification, the question is about the best way to resolve data
ViewerType.js
const Viewer = new GraphQLObjectType({
name: 'Viewer',
fields: () => ({
Seeker: {
type: SeekerConnection,
args: _.assign({
seekerId: { type: GraphQLID },
status: { type: GraphQLString },
shortlisted: { type: GraphQLInt },
}, connectionArgs),
resolve: (obj, args, auth, rootValue) => {
const filterArgs = getFilters(args) || {};
return connectionFromPromisedArray(getSeekers(filterArgs), args)
.then((data) => {
// getSeekers() provides all the data required for SeekerType fields and it's
JobsType fields
data.args = filterArgs;
return data;
}).catch(err => new Error(err));
},
},
}),
});
SeekerType.js
const SeekerType = new GraphQLObjectType({
name: 'SeekerType',
fields: () => ({
id: globalIdField('SeekerType', obj => obj._id),
userId: {
type: GraphQLID,
resolve: obj => obj._id,
},
email: { type: GraphQLString },
password: { type: GraphQLString },
firstName: { type: GraphQLString },
lastName: { type: GraphQLString },
imageLink: { type: GraphQLString },
education: { type: GraphQLString },
address: { type: GraphQLString },
jobs: {
type: new GraphQLList(JobType),
},
}),
interfaces: [nodeInterface],
});
getSeekers() provide complete data as graphql fields format with nested
jobs field data too
const getSeekers = filterArgs => new Promise((resolve, reject) => {
if (Object.keys(filterArgs).length === 0) {
Seeker.find(filterArgs, { password: 0 }, (err, d) => {
if (err) return reject(err);
return resolve(d);
});
} else {
async.parallel([
(callback) => {
filterArgs._id = filterArgs.seekerId;
delete filterArgs.seekerId;
Seeker.find(filterArgs).lean()
.exec((err, d) => {
if (err) return callback(err);
if (err === null && d === null) return callback(null);
callback(null, d);
});
},
(callback) => {
filterArgs.seekerId = filterArgs._id;
delete filterArgs._id;
Applicant.find(filterArgs).populate('jobId').lean()
.exec((err, resp) => {
if (err) return callback(err);
callback(null, resp);
});
},
], (err, data) => {
const cleanedData = {
userData: data[0],
userJobMap: data[1],
};
const result = _.reduce(cleanedData.userData, (p, c) => {
if (c.isSeeker) {
const job = _.filter(cleanedData.userJobMap,
v => _.isEqual(v.seekerId, c._id));
const arr = [];
_.forEach(job, (i) => {
arr.push(i.jobId);
});
const t = _.assign({}, c, { jobs: arr });
p.push(t);
return p;
}
return reject('Not a Seekr');
}, []);
if (err) reject(err);
resolve(result);
// result have both SeekerType data and nested type
JobType data too.
});
}
});
I gather this to be a question about how to prevent overfetching related data...I.e. How not to necessarily request jobs data when querying the seeker.
This might have several motivations for optimization and security.
Considerations:
If the consumer (e.g. Web app) is under your control, you can simply avoid requesting the jobs field when querying seeker. As you may know, this is one of the stated goals of graphql to only return what is needed over the wire to the consumer, to minimize network traffic and do things in one trip. On the backend I would imagine the graphql engine is smart enough not to overfetch jobs data either, if it's not requested.
If your concern is more of security or unintentional overfetching by consumer apps out of your control, for example, then you can solve that by creating seperate queries and limiting access to them even. E.g. One query for seeker and another for seekerWithJobsData.
Another technique to consider is graphql directives which offer an include switch that can be used to conditionally serve specific fields. One advantage of using this technique in your scenario might be to allow a convenient way to conditionally display multiple fields in multiple queries depending on the value of a single boolean e.g. JobSearchFlag=false. Read here for an overview of directives: http://graphql.org/learn/queries/
I am not sure I completely understand the question but it seems to me you're loading both seeker and job types info on one level. You should load both of them on demand.
On the seeker level, you only get the seeker information, and you can get the IDs of any records related to that seeker. For example, job types ids (if a seeker has many job types)
On the job type level, when used as a nested level for one seeker, you can use those ids to fetch the actual records. This would make the fetching of job types record on-demand when the query asks for it.
The ID to record fetching can be cached and batched with a library like dataloader

GraphQL : Implementing windowed pagination for regular list

I'm trying to implement a windowed pagination using a "List". I don't need the cursor based solution with connections, because I need to show numbered pages to the user.
There are "User" and "Post" objects."User" has one-to-many relation to "Post".
Using graphql-js for schema,
here is my schema for userType and postType:
var userType = new GraphQLObjectType({
name: 'User',
fields: () => ({
id: globalIdField('User'),
posts: {
type: new GraphQLList(postType),
args: {
page:{
type: GraphQLInt,
defaultValue: 0
}
},
resolve: (_, args) => {
//code to return relevant result set
},
},
totalPosts:{
type: GraphQLInt,
resolve: () => {
//code to return total count
}
},
}),
interfaces: [nodeInterface],
});
var postType = new GraphQLObjectType({
name: 'Post',
fields: () => ({
id: globalIdField('Post'),
name: {type: GraphQLString},
//other fields
}),
interfaces: [nodeInterface],
});
Please notice the "totalPosts" field in "userType". Since there is going to be other Lists for the user,with the same paging needs, I'm going to end up maintaining lot of "total{Type}" variables in the fragment. This can be solved if I can send the totalCount within the List result somehow.
https://github.com/facebook/graphql/issues/4 this issue talks about implementing a wrapper over the List to include the totalCount in the result set.
I tried creating a wrapper like this:
var postList = new GraphQLObjectType({
name: 'PostList',
fields:()=>({
count: {
type: GraphQLInt,
resolve: ()=>getPosts().length //this is total count
},
edges: {
type: new GraphQLList(postType),
resolve: () => {
return getPosts() ; // this is results for the page, though I don't know how to use 'page' argument here
},
}
}),
interfaces: [nodeInterface],
});
but how should I connect this to the userType's posts field? And how can I use a 'page' argument on this wrapper, like I have in original userType?
how should I connect this to the userType's posts field? And how can I use a 'page' argument on this wrapper, like I have in original userType?
One simple way to implement what you're trying to do is to define a dumb wrapper type postList like this:
var postList = new GraphQLObjectType({
name: 'PostList',
fields:()=>({
count: { type: GraphQLInt },
edges: { type: new GraphQLList(postType) }
// Consider renaming 'edges'. In your case, it's a list, not a
// connection. So, it can cause confusion in the long run.
}),
});
Then in the userType definition, add a field of that wrapper type and define its resolve function like below. As for argument page, just describe it while defining the field type posts.
posts: {
type: postList,
args: {
page:{
type: GraphQLInt,
defaultValue: 0
},
...otherArgs
},
resolve: async (_, {page, ...otherArgs}) => {
// Get posts for the given page number.
const posts = await db.getPosts(page);
// Prepare a server-side object, which corresponds to GraphQL
// object type postList.
const postListObj = {
count: posts.length,
edges: posts
};
// Consider renaming 'edges'. In your case, it's a list, not a
// connection. So, it can cause confusion in the long run.
},
},

How to authenticate in relay

what is the correct point to authenticate a user ?
going by the relay starter kit as an example.
this would seem like be the point to query (i have added the args id )
var queryType = new GraphQLObjectType({
name: 'Query',
fields: () => ({
node: nodeField,
// Add your own root fields here
viewer: {
args: {
id: {
type: GraphQLString
},
},
type: userType,
resolve: (_, args) => getViewer(args.id),
},
}),
});
then in the database do something like
getViewer: (id) => id === viewer.id ? viewer : null,
now its this point where it's falling apart, where would be the place to request the id be made from ? i would assume the route
export default class extends Relay.Route {
static queries = {
viewer: () => Relay.QL`
query {
viewer(id:"1")
}
`,
};
static routeName = 'AppHomeRoute';
}
this isn't working.
First you need to drop an auth middleware into your server (http://passportjs.org/ for instance).Then you have to pass the auth information to the graphql middleware (read about how to do it here https://github.com/graphql/express-graphql#advanced-options) and you can finally access that information using the 3rd argument to the resolve(parentValue, args, -->session) function. Here's what the actual auth endpoint could look like https://github.com/igorsvee/react-relay-example/blob/master/server/routes.js#L29-L51

Resources