impress-2020/src/server/index.js

446 lines
12 KiB
JavaScript
Raw Normal View History

const { gql } = require("apollo-server");
2020-04-22 11:51:36 -07:00
const connectToDb = require("./db");
const buildLoaders = require("./loaders");
const neopets = require("./neopets");
2020-05-23 12:47:06 -07:00
const {
capitalize,
getPoseFromPetState,
getPoseFromPetData,
2020-05-23 12:47:06 -07:00
getEmotion,
getGenderPresentation,
} = require("./util");
2020-04-22 11:51:36 -07:00
const typeDefs = gql`
2020-04-23 01:08:00 -07:00
enum LayerImageSize {
SIZE_600
SIZE_300
SIZE_150
}
2020-05-23 12:47:06 -07:00
"""
The poses a PetAppearance can take!
"""
enum Pose {
HAPPY_MASC
SAD_MASC
SICK_MASC
HAPPY_FEM
SAD_FEM
SICK_FEM
UNCONVERTED
UNKNOWN # for when we have the data, but we don't know what it is
}
"""
A pet's gender presentation: masculine or feminine.
Neopets calls these "male" and "female", and I think that's silly and not wise
to propagate further, especially in the context of a strictly visual app like
Dress to Impress! This description isn't altogether correct either, but idk
what's better :/
"""
enum GenderPresentation {
MASCULINE
FEMININE
}
"""
A pet's emotion: happy, sad, or sick.
Note that we don't ever show the angry emotion on Dress to Impress, because
we don't have the data: it's impossible for a pet's passive emotion on the
pet lookup to be angry!
"""
enum Emotion {
HAPPY
SAD
SICK
}
2020-04-22 11:51:36 -07:00
type Item {
id: ID!
name: String!
description: String!
2020-04-22 14:55:12 -07:00
thumbnailUrl: String!
appearanceOn(speciesId: ID!, colorId: ID!): ItemAppearance
2020-04-23 01:08:00 -07:00
}
type PetAppearance {
2020-05-02 20:48:32 -07:00
id: ID!
petStateId: ID!
bodyId: ID!
2020-05-23 12:47:06 -07:00
pose: Pose!
genderPresentation: GenderPresentation # deprecated
emotion: Emotion # deprecated
2020-05-02 20:48:32 -07:00
approximateThumbnailUrl: String!
layers: [AppearanceLayer!]!
}
type ItemAppearance {
layers: [AppearanceLayer!]!
2020-04-23 14:44:06 -07:00
restrictedZones: [Zone!]!
2020-04-23 01:08:00 -07:00
}
type AppearanceLayer {
2020-04-23 01:08:00 -07:00
id: ID!
zone: Zone!
imageUrl(size: LayerImageSize): String
2020-05-11 21:19:34 -07:00
"""
This layer as a single SVG, if available.
This might not be available if the asset isn't converted yet by Neopets,
or if it's not as simple as a single SVG (e.g. animated).
"""
svgUrl: String
2020-04-23 01:08:00 -07:00
}
type Zone {
id: ID!
depth: Int!
label: String!
2020-04-22 11:51:36 -07:00
}
2020-04-25 01:55:48 -07:00
type ItemSearchResult {
query: String!
items: [Item!]!
}
2020-04-25 03:42:05 -07:00
type Color {
id: ID!
name: String!
}
type Species {
id: ID!
name: String!
}
type SpeciesColorPair {
species: Species!
color: Color!
}
type Outfit {
species: Species!
color: Color!
pose: Pose!
items: [Item!]!
}
2020-04-22 11:51:36 -07:00
type Query {
allColors: [Color!]! @cacheControl(maxAge: 10800) # Cache for 3 hours
allSpecies: [Species!]! @cacheControl(maxAge: 10800) # Cache for 3 hours
allValidSpeciesColorPairs: [SpeciesColorPair!]! # deprecated
2020-04-22 11:51:36 -07:00
items(ids: [ID!]!): [Item!]!
2020-04-25 01:55:48 -07:00
itemSearch(query: String!): ItemSearchResult!
itemSearchToFit(
query: String!
speciesId: ID!
colorId: ID!
offset: Int
limit: Int
): ItemSearchResult!
2020-05-23 12:47:06 -07:00
petAppearance(speciesId: ID!, colorId: ID!, pose: Pose!): PetAppearance
petAppearances(speciesId: ID!, colorId: ID!): [PetAppearance!]!
petOnNeopetsDotCom(petName: String!): Outfit
2020-04-22 11:51:36 -07:00
}
`;
const resolvers = {
Item: {
name: async (item, _, { itemTranslationLoader }) => {
// Search queries pre-fill this!
if (item.name) return item.name;
const translation = await itemTranslationLoader.load(item.id);
2020-04-22 11:51:36 -07:00
return translation.name;
},
description: async (item, _, { itemTranslationLoader }) => {
const translation = await itemTranslationLoader.load(item.id);
return translation.description;
},
appearanceOn: async (
item,
{ speciesId, colorId },
{ petTypeLoader, itemSwfAssetLoader }
) => {
2020-04-23 01:08:00 -07:00
const petType = await petTypeLoader.load({
speciesId: speciesId,
colorId: colorId,
2020-04-23 01:08:00 -07:00
});
2020-05-27 00:46:55 -07:00
const allSwfAssets = await itemSwfAssetLoader.load({
itemId: item.id,
2020-04-23 01:08:00 -07:00
bodyId: petType.bodyId,
});
2020-05-27 00:46:55 -07:00
if (allSwfAssets.length === 0) {
// If there's no assets at all, treat it as non-fitting: no appearance.
// (If there are assets but they're non-SWF, we'll treat this as
// fitting, but with an *empty* appearance.)
return null;
}
2020-05-27 00:46:55 -07:00
const swfAssets = allSwfAssets.filter((sa) => sa.url.endsWith(".swf"));
2020-04-23 14:44:06 -07:00
const restrictedZones = [];
for (const [i, bit] of Array.from(item.zonesRestrict).entries()) {
if (bit === "1") {
const zone = { id: i + 1 };
restrictedZones.push(zone);
}
}
return { layers: swfAssets, restrictedZones };
2020-04-23 01:08:00 -07:00
},
},
PetAppearance: {
id: ({ petType, petState }) => {
const { speciesId, colorId } = petType;
2020-05-23 12:47:06 -07:00
const pose = getPoseFromPetState(petState);
return `${speciesId}-${colorId}-${pose}`;
},
petStateId: ({ petState }) => petState.id,
bodyId: ({ petType }) => petType.bodyId,
2020-05-23 12:47:06 -07:00
pose: ({ petState }) => getPoseFromPetState(petState),
genderPresentation: ({ petState }) =>
2020-05-23 12:47:06 -07:00
getGenderPresentation(getPoseFromPetState(petState)),
emotion: ({ petState }) => getEmotion(getPoseFromPetState(petState)),
2020-05-02 20:48:32 -07:00
approximateThumbnailUrl: ({ petType, petState }) => {
return `http://pets.neopets.com/cp/${petType.basicImageHash}/${petState.moodId}/1.png`;
},
layers: async ({ petState }, _, { petSwfAssetLoader }) => {
const swfAssets = await petSwfAssetLoader.load(petState.id);
return swfAssets;
},
},
AppearanceLayer: {
2020-04-23 01:08:00 -07:00
zone: async (layer, _, { zoneLoader }) => {
const zone = await zoneLoader.load(layer.zoneId);
return zone;
},
imageUrl: (layer, { size }) => {
if (!layer.hasImage) {
return null;
}
const sizeNum = size.split("_")[1];
const rid = layer.remoteId;
const paddedId = rid.padStart(12, "0");
const rid1 = paddedId.slice(0, 3);
const rid2 = paddedId.slice(3, 6);
const rid3 = paddedId.slice(6, 9);
const time = Number(new Date(layer.convertedAt));
return (
`https://impress-asset-images.s3.amazonaws.com/${layer.type}` +
`/${rid1}/${rid2}/${rid3}/${rid}/${sizeNum}x${sizeNum}.png?v2-${time}`
);
2020-04-23 01:08:00 -07:00
},
2020-05-23 11:32:05 -07:00
svgUrl: async (layer, _, { svgLogger }) => {
2020-05-11 21:19:34 -07:00
const manifest = await neopets.loadAssetManifest(layer.url);
if (!manifest) {
2020-05-23 11:32:05 -07:00
svgLogger.log("no-manifest");
2020-05-11 21:19:34 -07:00
return null;
}
if (manifest.assets.length !== 1) {
2020-05-23 11:32:05 -07:00
svgLogger.log(`wrong-asset-count:${manifest.assets.length}!=1`);
2020-05-11 21:19:34 -07:00
return null;
}
const asset = manifest.assets[0];
if (asset.format !== "vector") {
2020-05-23 11:32:05 -07:00
svgLogger.log(`wrong-asset-format:${asset.format}`);
2020-05-11 21:19:34 -07:00
return null;
}
if (asset.assetData.length !== 1) {
2020-05-23 11:32:05 -07:00
svgLogger.log(`wrong-assetData-length:${asset.assetData.length}!=1`);
2020-05-11 21:19:34 -07:00
return null;
}
2020-05-23 11:32:05 -07:00
svgLogger.log("success");
2020-05-11 21:19:34 -07:00
const assetDatum = asset.assetData[0];
const url = new URL(assetDatum.path, "http://images.neopets.com");
return url.toString();
},
2020-04-23 01:08:00 -07:00
},
Zone: {
label: async (zone, _, { zoneTranslationLoader }) => {
const zoneTranslation = await zoneTranslationLoader.load(zone.id);
return zoneTranslation.label;
},
2020-04-22 11:51:36 -07:00
},
2020-04-25 03:42:05 -07:00
Color: {
name: async (color, _, { colorTranslationLoader }) => {
const colorTranslation = await colorTranslationLoader.load(color.id);
2020-04-25 04:33:05 -07:00
return capitalize(colorTranslation.name);
2020-04-25 03:42:05 -07:00
},
},
Species: {
name: async (species, _, { speciesTranslationLoader }) => {
const speciesTranslation = await speciesTranslationLoader.load(
species.id
);
2020-04-25 04:33:05 -07:00
return capitalize(speciesTranslation.name);
2020-04-25 03:42:05 -07:00
},
},
2020-04-22 11:51:36 -07:00
Query: {
2020-04-25 03:42:05 -07:00
allColors: async (_, { ids }, { loadAllColors }) => {
const allColors = await loadAllColors();
return allColors;
},
allSpecies: async (_, { ids }, { loadAllSpecies }) => {
const allSpecies = await loadAllSpecies();
return allSpecies;
},
allValidSpeciesColorPairs: async (_, __, { loadAllPetTypes }) => {
const allPetTypes = await loadAllPetTypes();
const allPairs = allPetTypes.map((pt) => ({
color: { id: pt.colorId },
species: { id: pt.speciesId },
}));
return allPairs;
},
items: async (_, { ids }, { itemLoader }) => {
const items = await itemLoader.loadMany(ids);
2020-04-23 01:08:00 -07:00
return items;
2020-04-24 21:17:03 -07:00
},
itemSearch: async (_, { query }, { itemSearchLoader }) => {
const items = await itemSearchLoader.load(query);
2020-04-25 01:55:48 -07:00
return { query, items };
},
itemSearchToFit: async (
_,
2020-04-25 01:55:48 -07:00
{ query, speciesId, colorId, offset, limit },
{ petTypeLoader, itemSearchToFitLoader }
) => {
const petType = await petTypeLoader.load({ speciesId, colorId });
const { bodyId } = petType;
2020-04-25 01:55:48 -07:00
const items = await itemSearchToFitLoader.load({
query,
bodyId,
offset,
limit,
});
return { query, items };
2020-04-23 01:08:00 -07:00
},
petAppearance: async (
_,
2020-05-23 12:47:06 -07:00
{ speciesId, colorId, pose },
2020-05-02 20:48:32 -07:00
{ petTypeLoader, petStateLoader }
) => {
const petType = await petTypeLoader.load({
speciesId,
colorId,
});
const petStates = await petStateLoader.load(petType.id);
// TODO: This could be optimized into the query condition 🤔
2020-05-23 12:47:06 -07:00
const petState = petStates.find((ps) => getPoseFromPetState(ps) === pose);
if (!petState) {
return null;
}
return { petType, petState };
},
petAppearances: async (
_,
{ speciesId, colorId },
2020-05-02 20:48:32 -07:00
{ petTypeLoader, petStateLoader }
) => {
const petType = await petTypeLoader.load({
speciesId,
colorId,
});
const petStates = await petStateLoader.load(petType.id);
2020-05-02 20:48:32 -07:00
return petStates.map((petState) => ({ petType, petState }));
},
petOnNeopetsDotCom: async (_, { petName }) => {
const [petMetaData, customPetData] = await Promise.all([
neopets.loadPetMetaData(petName),
neopets.loadCustomPetData(petName),
]);
const outfit = {
species: { id: customPetData.custom_pet.species_id },
color: { id: customPetData.custom_pet.color_id },
pose: getPoseFromPetData(petMetaData, customPetData),
items: Object.values(customPetData.object_info_registry).map((o) => ({
id: o.obj_info_id,
})),
};
return outfit;
},
2020-04-22 11:51:36 -07:00
},
};
2020-05-23 11:32:05 -07:00
let lastSvgLogger = null;
const svgLogging = {
requestDidStart() {
return {
willSendResponse({ operationName }) {
const logEntries = lastSvgLogger.entries;
if (logEntries.length === 0) {
return;
}
console.log(`[svgLogger] Operation: ${operationName}`);
const logEntryCounts = {};
for (const logEntry of logEntries) {
logEntryCounts[logEntry] = (logEntryCounts[logEntry] || 0) + 1;
}
const logEntriesSortedByCount = Object.entries(logEntryCounts).sort(
(a, b) => b[1] - a[1]
);
for (const [logEntry, count] of logEntriesSortedByCount) {
console.log(`[svgLogger] - ${logEntry}: ${count}`);
}
},
};
},
};
const config = {
2020-04-22 11:51:36 -07:00
typeDefs,
resolvers,
context: async () => {
const db = await connectToDb();
2020-05-23 11:32:05 -07:00
const svgLogger = {
entries: [],
log(entry) {
this.entries.push(entry);
},
};
lastSvgLogger = svgLogger;
return {
2020-05-23 11:32:05 -07:00
svgLogger,
...buildLoaders(db),
};
2020-04-22 11:51:36 -07:00
},
2020-04-23 01:09:17 -07:00
2020-05-23 11:32:05 -07:00
plugins: [svgLogging],
2020-04-23 01:09:17 -07:00
// Enable Playground in production :)
introspection: true,
playground: {
endpoint: "/api/graphql",
},
};
2020-04-22 11:51:36 -07:00
if (require.main === module) {
const { ApolloServer } = require("apollo-server");
const server = new ApolloServer(config);
2020-04-22 11:51:36 -07:00
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
}
module.exports = { config };