How to return distinct data using gql from apollo-boost - graphql-js

I am working with a React component implemented with TypeScript where I am querying some data using gql from apollo-boost library. First time user so have little knowledge.
const GET_COUNTRIES = gql`
query GET_COUNTRIES {
users {
(country)
}
}
`;
How to get the distinct countries from this query? Tried with distinct / distinct_on. None of them worked.

Related

Prisma: Finding items where two fields have the same value

I would like to find items in a Prisma db where the values for two columns are the same. The use case is to compare the 'created_at' and 'updated_at' fields to find items that have never been updated after their initial creation. In raw SQL I would do something like:
select updated_at,
cast(sign(sum(case when updated_at = created_at then
1
else
0
end)) as int) as never_modified
from tab
group by updated_at
Is it possible to achieve this in Prisma?
You would need to use Raw Queries to compare time values from the same table.
Here's an example of how you could achieve this, assuming a PostgreSQL database for the following query.
import { PrismaClient } from '#prisma/client'
const prisma = new PrismaClient()
async function initiateDatesComparisonRawQuery() {
const response =
await prisma.$queryRaw`SELECT * FROM "public"."Project" WHERE "created_at" = "updated_at";`;
console.log(response);
}
await initiateDatesComparisonRawQuery();
you can use the preview feature fieldReference of prisma.
schema.prisma
generator client {
provider = "prisma-client-js"
previewFeatures = ["fieldReference"]
}
your code
prisma.project.findMany({
where: { created_at: prisma.project.fields.updated_at }
})

Relational data in react-query

I have a REST api which has this endpoint for getting an assignment -
'/classes/<str:code>/assignments/<int:assignment_id>'
I have created a custom hook for querying an Assignment:
const getAssignment = async ({ queryKey }) => {
const [, code, assignmentId] = queryKey
const { data } = await api.get(`/classes/${code}/assignments/${assignmentId}`)
return data
}
export default function useAssignment(code, assignmentId) {
return useQuery(['assignment', code, assignmentId], getAssignment)
}
This works as expected, but is this the right way to deal with relational data in react-query?
code looks right to me. react-query doesn't have a normalized cache, just a document cache. So if you request assignments with a different query key, e.g. assignments for a user, they will be cache separately.
The straight forward approach to tackle this would then be to structure your query keys in a way that you can invalidate everything at the same time.

Rewrite raw PostgreSQL query to use SelectQueryBuilder from TypeORM

I've written this query that fetches user ids (that's for now, cos I actually need way more fields from the user table as well as from another table called image that is related the user table).
The problem with this query is that it returns a plain object and I need an entity object, I mean I know I could just deserialise it to whatever model I need, but the thing also is that I normally deserialise entity to a required response model. Also, I would like to avoid making
a couple of requests: one fetching user ids and the other fetching right entity objects by those ids using queryBuilder.
So, it seems that one possible solution would be to rewrite this query to make use of queryBuilder straight away.
const matchedUsers = await this.usersRepository.query(
`
SELECT id FROM users
WHERE id IN (
SELECT "usersId" FROM locations_available_fighters_users
WHERE "locationsId" IN (
SELECT "locationsId" FROM locations_available_fighters_users
WHERE "usersId" = ${ me.getId() }
)
) AND is_active IS TRUE
AND id != ${ me.getId() }
AND weight = '${ me.getWeight() }'
AND gender = '${ me.getGender() }'
AND role_name = '${ me.getRoleName() }';
`
);
If the problems you're trying to solve are:
Use a single query
Get the returned data as entity objects rather than raw results
Use QueryBuilder to avoid writing raw queries
I believe what you should be looking into is typeorm subqueries.
For the query you posted in the question, you can try something like below using QueryBuilder:
// Subquery for your inner most subquery,
const locationsQb = connection.getRepository(LocationsAvailableFightersUser)
.createQueryBuilder("lafu_1")
.select("lafu_1.locationsId")
.where("lafu_1.usersId = :usersID", { usersID: me.getId() });
// Subquery for your middle subquery,
const usersQb = connection.getRepository(LocationsAvailableFightersUser)
.createQueryBuilder("lafu_2")
.select("lafu_2.usersId")
.where("lafu_2.locationsId IN (" + locationsQb.getQuery() + ")");
// Query for retrieving `User` entities as you needed,
const matchedUsers = await connection.getRepository(User)
.createQueryBuilder("user")
.where("user.id IN (" + usersQb.getQuery() + ")")
.setParameters(locationsQb.getParameters())
.getMany();
Here I assumed that,
LocationsAvailableFightersUser is the entity for locations_available_fighters_users table
User is the entity for users table
Hope this helps you. Cheers 🍻 !!!

Query Firestore documents with role based security via Flutter

I´ve a role based data model on Firestore according to googles suggestion here: https://firebase.google.com/docs/firestore/solutions/role-based-access
Security rules are set up correctly and work fine. But now I´ve the problem on how to query for the roles.
This is my data model (one sample document):
id: "1234-5678-91234",
roles:
userId_1:"owner",
userId_2:"editor
title: "This is a sample document"
And this is my Firestore Query in Flutter which gets all documents for a specific user by its ID if the user has assigned the role "owner" for the document:
return firestore
.collection(path)
.where("roles.${user.firebaseUserId}", isEqualTo: "owner")
.snapshots().map((snapshot) {
return snapshot.documents.map((catalog) {
return SomeDocumentObject(...);
}).toList();
});
My problem now is, that I need some kind of "OR" clause - which does not exist as far as I know. The query above only retrieves documents for users with role "owner" but I need a query that also retrieves the document if the userId is associated with the role "editor".
I´ve tried "arrayContains:" which also doesn´t seem to work (cause it´s a map).
I´ve read about solutions with two independent queries which doesn´t sound like a good solution due to a lot of overhead.
Maybe someone of you have a hint for me? :)
Thanks & best,
Michael
Firestore doesn't currently have any logical OR operations. You'll have to perform two queries, one for each condition, and merge the results of both queries in the client app.
This is the final solution using RxDart, Observables and .combineLatest() - maybe it helps someone out there:
#override
Stream<List<Catalog>> catalogs(User user) {
// Retrieve all catalogs where user is owner
Observable<QuerySnapshot> ownerCatalogs = Observable(firestore
.collection(path)
.where("roles.${user.firebaseUserId}", isEqualTo: "owner")
.snapshots());
// Retrieve all catalogs where user is editor
Observable<QuerySnapshot> editorCatalogs = Observable(firestore
.collection(path)
.where("roles.${user.firebaseUserId}", isEqualTo: "editor")
.snapshots());
// Convert merged stream to list of catalogs
return Observable.combineLatest([ownerCatalogs, editorCatalogs],
(List<QuerySnapshot> snapshotList) {
List<Catalog> catalogs = [];
snapshotList.forEach((snapshot) {
snapshot.documents.forEach((DocumentSnapshot catalog) {
catalogs.add(Catalog(
id: catalog.documentID,
title: catalog.data['title'],
roles: catalog.data['roles'],
));
});
});
return catalogs;
}).asBroadcastStream();
}

Applying query filter like the one in codelab (Cloud Firestore) is not working

I'm using firestore for my project to store data , my issue is that i can not
filter data just the way codelab filter does .The result of that query gives me the whole collections docs which means the filter is not working.
I've tried many workarounds and find out that only when I cascade whereEqualto()
methods in one line I get what I want of specific docs , but this approach (cascading whereEqualTo inline) is not flexible when giving the user a way to filter searches.I just want to know why that code is not working for me.
// Does not work
Query query = mFirestore.collection("restaurants");
// Category (equality filter)
if (filters.hasCategory()) {
query = query.whereEqualTo("category", filters.getCategory());
}
// City (equality filter)
if (filters.hasCity()) {
query = query.whereEqualTo("city", filters.getCity());
}
This works:
query.whereEqualTo("realEstateType", realEstateType).whereEqualTo("propertyStatus", propertyStatus).whereEqualTo("propertyPhysicalStatus", propertyPhysicalConditionS).addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
}
}
});
I figured it out ,It seems that I was not assigning to query object the filter as follows:
query = query.whereEqualTo("fieldPath" , ...);