Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

api gardening #1147

Merged
merged 2 commits into from
Aug 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 0 additions & 7 deletions .example.env
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,3 @@
MONGODB_URI=mongodb://127.0.0.1:27017/toiletmap
# Use this database in migration scripts
DATABASE_NAME=toiletmap

# UI
# If you wish to avoid running a local API you can proxy to a remote
# PROXY=https://some.remote.api

# Connect to GA in prod
REACT_APP_GOOGLE_MAPS_API_KEY=
7 changes: 0 additions & 7 deletions api/README.md

This file was deleted.

6 changes: 0 additions & 6 deletions api/index.js

This file was deleted.

18 changes: 1 addition & 17 deletions next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,4 @@ module.exports = {
// your project has ESLint errors.
ignoreDuringBuilds: true,
},
webpack: (config, { isServer }) => {
// config.module.rules.push({
// test: /\.(graphql|gql)$/,
// exclude: /node_modules/,
// loader: 'graphql-tag/loader',
// });
return config;
},
async rewrites() {
return [
{
source: '/api/:path*',
destination: 'http://localhost:4000/:path*' // Proxy to Backend
}
]
}
}
};
33 changes: 10 additions & 23 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
"build": "next build",
"dev": "next dev",
"start": "next start",
"api": "node -r dotenv/config ./api/index.js",
"lint": "eslint . && stylelint \"src/**/*.css\"",
"format": "prettier --write \"./**/*.{js,json}\"",
"test": "jest",
Expand Down Expand Up @@ -51,7 +50,7 @@
"@material-ui/icons": "4.11.2",
"@rehooks/component-size": "1.0.3",
"@styled-system/prop-types": "5.1.5",
"apollo-server": "2.24.1",
"apollo-server-micro": "2.25.2",
Copy link
Member

@ob6160 ob6160 Aug 3, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please excuse my ignorance - just wondering what apollo-server-micro is doing that apollo-server wasn't able to do?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Vercel/Next.js uses micro to front the api functions, so it is the preferred integration.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah right right sounds good

"auth0-js": "9.16.2",
"chart.js": "2.9.4",
"d3-scale": "3.3.0",
Expand All @@ -68,6 +67,7 @@
"jwks-rsa": "2.0.4",
"leaflet": "1.7.1",
"lodash": "4.17.21",
"micro": "9.3.4",
"mongoose": "5.12.14",
"mongoose-paginate": "5.0.3",
"next": "11.0.1",
Expand All @@ -92,8 +92,8 @@
},
"devDependencies": {
"@apollo/client": "3.4.1",
"@commitlint/cli": "12.1.4",
"@commitlint/config-conventional": "12.1.4",
"@commitlint/cli": "13.1.0",
"@commitlint/config-conventional": "13.1.0",
"@graphql-codegen/cli": "1.21.8",
"@graphql-codegen/import-types-preset": "1.18.6",
"@graphql-codegen/typescript": "1.23.0",
Expand All @@ -103,11 +103,11 @@
"@mapbox/geojson-area": "0.2.2",
"@mapbox/geojson-rewind": "0.5.1",
"@shelf/jest-mongodb": "1.3.4",
"@types/jest": "26.0.23",
"@types/node": "15.12.4",
"@types/jest": "26.0.24",
"@types/node": "16.4.10",
"@types/puppeteer": "5.4.4",
"@types/react": "17.0.11",
"@types/react-dom": "17.0.8",
"@types/react": "17.0.15",
"@types/react-dom": "17.0.9",
"@types/react-leaflet": "2.8.1",
"@types/styled-system": "5.1.11",
"apollo-server-testing": "2.24.1",
Expand All @@ -119,7 +119,7 @@
"geojson-precision": "1.0.0",
"graphql-codegen-apollo-next-ssr": "1.6.1",
"http-proxy-middleware": "2.0.1",
"husky": "6.0.0",
"husky": "7.0.1",
"jest-puppeteer": "5.0.3",
"lint-staged": "11.1.1",
"migrate-mongo": "8.2.3",
Expand All @@ -135,23 +135,10 @@
"stylelint-config-standard": "22.0.0",
"topojson-server": "3.0.1",
"topojson-simplify": "3.0.3",
"typescript": "4.3.4",
"typescript": "4.3.5",
"uuid": "8.3.2",
"webpack": "5.40.0"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version",
"ie 11"
]
},
"resolutions": {
"graphql": "14.7.0"
},
Expand Down
2 changes: 1 addition & 1 deletion src/api/db/area.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,4 @@ AreaSchema.statics.containing = async function (coords) {
return areas.sort((a, b) => b.priority - a.priority);
};

module.exports = new mongoose.model('Area', AreaSchema);
module.exports = mongoose.models.Area || new mongoose.model('Area', AreaSchema);
2 changes: 1 addition & 1 deletion src/api/db/loo.js
Original file line number Diff line number Diff line change
Expand Up @@ -211,4 +211,4 @@ LooSchema.statics.getAreasCounters = async function () {
return areas;
};

module.exports = new mongoose.model('NewLoo', LooSchema);
module.exports = mongoose.models.NewLoo || new mongoose.model('NewLoo', LooSchema);
2 changes: 1 addition & 1 deletion src/api/db/mapgeo.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,4 @@ const MapGeoSchema = new mongoose.Schema(

MapGeoSchema.index({ areaType: 'text' });

module.exports = new mongoose.model('MapGeo', MapGeoSchema);
module.exports = mongoose.models.MapGeo || new mongoose.model('MapGeo', MapGeoSchema);
2 changes: 1 addition & 1 deletion src/api/db/report.js
Original file line number Diff line number Diff line change
Expand Up @@ -225,4 +225,4 @@ ReportSchema.statics.getCounters = async function () {
};
};

module.exports = new mongoose.model('NewReport', ReportSchema);
module.exports = mongoose.models.NewReport || new mongoose.model('NewReport', ReportSchema);
2 changes: 1 addition & 1 deletion src/api/directives/RedactionDirective.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { SchemaDirectiveVisitor } = require('apollo-server');
const { SchemaDirectiveVisitor } = require('apollo-server-micro');
const { defaultFieldResolver } = require('graphql');
const config = require('../config');

Expand Down
2 changes: 1 addition & 1 deletion src/api/directives/RequirePermissionDirective.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const {
SchemaDirectiveVisitor,
AuthenticationError,
} = require('apollo-server');
} = require('apollo-server-micro');
const { defaultFieldResolver } = require('graphql');
const config = require('../config');

Expand Down
4 changes: 2 additions & 2 deletions src/api/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { ApolloServer, gql } = require('apollo-server');
const { ApolloServer, gql } = require('apollo-server-micro');
const jwt = require('jsonwebtoken');
const jwksClient = require('jwks-rsa');

Expand Down Expand Up @@ -67,5 +67,5 @@ const apollo = new ApolloServer({
playground: { ...config.graphql.playground },
introspection: true,
});

console.log(apollo)
module.exports = apollo;
5 changes: 4 additions & 1 deletion src/api/typeDefs.graphql → src/api/typeDefs.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { gql } from 'apollo-server-micro'
export default gql(`
scalar DateTime
scalar OpeningTimes

Expand Down Expand Up @@ -191,7 +193,7 @@ type Proportions {
Statistics for a certain area.
"""
type AreaStats {
"The area's identifier. Note that only the `name` will be passed with this field."
"The area's identifier. Note that only the 'name' will be passed with this field."
area: AdminGeo!
"The total number of loos in this area"
totalLoos: Int!
Expand Down Expand Up @@ -323,3 +325,4 @@ type Mutation {
@auth(requires: SUBMIT_REPORT)
submitVerificationReport(id: ID): ReportMutationResponse
}
`)
75 changes: 75 additions & 0 deletions src/pages/api/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { ApolloServer, gql } from 'apollo-server-micro';
import { makeExecutableSchema } from '@graphql-tools/schema';
import jwt from 'jsonwebtoken';
import jwksClient from 'jwks-rsa';

import settings from '../../api/config';

import resolvers from '../../api/resolvers';
import {
RequirePermissionDirective,
RedactionDirective,
} from '../../api/directives';

import typeDefs from '../../api/typeDefs';

const client = jwksClient({
jwksUri: settings.auth0.jwksUri,
});

const { connect } = require('../../api/db');
connect(process.env.MONGODB_URI);

function getKey(header, cb) {
client.getSigningKey(header.kid, function (err, key) {
var signingKey = key.publicKey || key.rsaPublicKey;
cb(null, signingKey);
});
}

const options = {
audience: settings.auth0.audience,
issuer: settings.auth0.issuer,
algorithms: settings.auth0.algorithms,
};

// Add GraphQL API
const server = new ApolloServer({
schema: makeExecutableSchema({
typeDefs,
resolvers,
schemaDirectives: {
auth: RequirePermissionDirective,
redact: RedactionDirective,
},
}),
context: async ({ req }) => {
let user = null;
const authorization = req.headers.authorization;
if (authorization) {
const token = authorization.replace('Bearer ', '');
user = await new Promise((resolve, reject) => {
jwt.verify(token, getKey, options, (err, decoded) => {
if (err) {
return reject(err);
}
resolve(decoded);
});
});
}
return {
user,
};
},
introspection: true,
});

export const config = {
api: {
bodyParser: false,
},
};

export default server.createHandler({
path: '/api',
});
11 changes: 5 additions & 6 deletions src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ import { getServerPageFindLooById, getServerPageFindLoosNearby, useFindLooById,
/**
* SSR Migration plan
* ---
*
*
* Look at getStaticProps to fetch loos for lat/lng at build time.
* Look at using getStaticProps to pre-fetch /loos/[id].
*
*
* Use ISR (https://nextjs.org/docs/basic-features/data-fetching#incremental-static-regeneration)
* ISR lets us regenerate loo pages and lat/lng loo list incrementally upon new requests
* Set revalidate to throttle this by n seconds.
Expand Down Expand Up @@ -52,15 +52,15 @@ const HomePage = ({ initialPosition, ...props }) => {
React.useEffect(() => {
window.localStorage.setItem(FILTERS_KEY, JSON.stringify(filters));
}, [filters]);

const [toiletData, setToiletData] = React.useState([]);
const variables = {
lat: mapState.center.lat,
lng: mapState.center.lng,
radius: Math.ceil(mapState.radius),
};
const router = useRouter();

/**
* Fetch nearby loo data when the map state changes.
* TODO: Try initial fetch using SSR.
Expand All @@ -75,7 +75,7 @@ const HomePage = ({ initialPosition, ...props }) => {
fetchNearbyLooData();
}, [mapState])


const { id: selectedLooId } = router.query;


Expand Down Expand Up @@ -116,7 +116,6 @@ const HomePage = ({ initialPosition, ...props }) => {
);

const isLooPage = router.pathname === '/loos/[id]';
console.log("AA", isLooPage, router.pathname)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks missed this

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Natch

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🙏

const [shouldCenter, setShouldCenter] = React.useState(isLooPage);

// set initial map center to toilet if on /loos/:id
Expand Down
Loading