Skip to content

Commit

Permalink
fix: rewritten loader logic so it orders owners by pets (#486)
Browse files Browse the repository at this point in the history
* rewritten loader logic so it orders owners by pets

* switched ids of owners so their order don't match up with pets

* moved sorting logic to sql query from code

* edited slides to reflect new logic
  • Loading branch information
GergoHorvathNearForm authored Aug 17, 2023
1 parent 6f49e06 commit bd8805f
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 13 deletions.
2 changes: 1 addition & 1 deletion migrations/002.do.sql
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
INSERT INTO owners (name) VALUES ('Jennifer'), ('Simon');
INSERT INTO pets (name, owner) VALUES ('Max', 1), ('Charlie', 2);
INSERT INTO pets (name, owner) VALUES ('Max', 2), ('Charlie', 1);
7 changes: 3 additions & 4 deletions slides.md
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,8 @@ export async function ownersByPetNames(db, petNames) {
INNER JOIN pets
ON pets.owner = owners.id
AND pets.name = ANY(${petNames})
ORDER BY
ARRAY_POSITION((${petNames}), pets.name)`
`
)
Expand Down Expand Up @@ -676,9 +678,7 @@ onResolution called
"errors": [
{
"message": "Invalid User ID",
"locations": [
{ "line": 2, "column": 3 }
],
"locations": [{ "line": 2, "column": 3 }],
"path": ["findUser"],
"extensions": {
"code": "USER_ID_INVALID",
Expand Down Expand Up @@ -797,7 +797,6 @@ await gateway.listen({ port: 4000 })

# Step 8: Solution / 2

```js
// index.js
import Fastify from 'fastify'
Expand Down
13 changes: 7 additions & 6 deletions src/step-04-n+1/lib/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@ export async function loadPets(db) {
export async function ownersByPetNames(db, petNames) {
const { rows } = await db.query(
SQL`
SELECT owners.*
FROM owners
INNER JOIN pets
ON pets.owner = owners.id
AND pets.name = ANY(${petNames})
`
SELECT owners.*
FROM owners
INNER JOIN pets
ON pets.owner = owners.id
AND pets.name = ANY(${petNames})
ORDER BY
ARRAY_POSITION((${petNames}), pets.name)`
)

return rows
Expand Down
4 changes: 2 additions & 2 deletions src/step-04-n+1/test/n+1.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ test('should return owner of the pet', async t => {
{
name: 'Max',
owner: {
name: 'Jennifer'
name: 'Simon'
}
},
{
name: 'Charlie',
owner: {
name: 'Simon'
name: 'Jennifer'
}
}
]
Expand Down

0 comments on commit bd8805f

Please sign in to comment.