-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathships.js
86 lines (74 loc) · 2.16 KB
/
ships.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import {zipObject, chain, map, filter} from 'lodash'
// create ships
const createShip = async (ship: Ship, client: Client) => {
const {id: oldId, name, attack = 0, agility = 0, hull = 0, shields = 0, actions = [], size, xws} = ship
const actionsFix =actions.map((action)=> `"${action}"`)
const result = await client.mutate(`{
ship: createShip(
oldId: ${oldId},
name: "${name}",
attack: ${attack || 0},
agility: ${agility},
hull: ${hull},
shields: ${shields},
actions: [${actionsFix.toString()}],
size: "${size}",
xws: "${xws}"
){
id
}
}`)
return result.ship.id
}
const findShip = async (ship: Ship, client: Client) => {
const result = await client.query(`{
allShips(
filter: {
oldId: ${ship.id}
}
) {
id
}
}`)
return result
}
export const connectShipsAndPilots = async(rawShips, newShips, rawPilots, newPilots, client) => {
return await map(rawShips, async(ship) => {
const newShipId = newShips[ship.id]
const newPilotIds = chain(rawPilots)
.filter(pilot => {
return pilot.ship === ship.name
})
.map(pilot => {
return newPilots[pilot.id]
})
.value()
return await map(newPilotIds, async(newPilotId) => {
const connectedShip = await connectShipsAndPilotsMutation(newShipId, newPilotId, client)
return connectedShip
})
})
}
const connectShipsAndPilotsMutation = async(shipId, pilotId, client) => {
const result = await client.mutate(`{
addToShipPilots(shipShipId: "${shipId}" pilotsPilotId: "${pilotId}") {
pilotsPilot{
id
}
}
}`)
return result
}
export const createShips = async (rawShips: Ship[], client: Client): Promise<IdMap> => {
const shipIds = await Promise.all(rawShips.map( async(ship) => {
// check if ship already exists
const existingShip = await findShip(ship, client)
// if ship doesn't exist, create it
if (existingShip.allShips.length === 0) {
return await createShip(ship, client)
} else {
return existingShip.allShips[0].id
}
}))
return zipObject(rawShips.map(ship => ship.id), shipIds)
}