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

Configurable path for prime core #119

Merged
merged 1 commit into from
Mar 15, 2019
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
10 changes: 6 additions & 4 deletions packages/prime-core/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export const createServer = async ({ port, connection }: ServerConfig) => {

if (config.sofaApi) {
app.use(
'/api',
`${config.path}api`,
sofa({
schema: external.schema,
ignore: ['Prime_Document'],
Expand All @@ -63,13 +63,15 @@ export const createServer = async ({ port, connection }: ServerConfig) => {

externalServer.applyMiddleware({
app,
path: `${config.path}graphql`,
cors: {
origin: true,
},
});

fields.forEach(
field => field.ui && app.use(`/prime/field/${field.type}`, express.static(field.ui))
field =>
field.ui && app.use(`${config.pathClean}/prime/field/${field.type}`, express.static(field.ui))
);

const apollo = new ApolloServer({
Expand All @@ -95,14 +97,14 @@ export const createServer = async ({ port, connection }: ServerConfig) => {
apollo.installSubscriptionHandlers(server);
apollo.applyMiddleware({
app,
path: '/prime/graphql',
path: `${config.path}prime/graphql`,
cors: {
origin: true,
},
});

previewRoutes(app);
serveUI(app, config);
serveUI(app);

return server.listen(port, () => {
log(`🚀 Server ready at http://localhost:${port}${apollo.graphqlPath}`);
Expand Down
17 changes: 17 additions & 0 deletions packages/prime-core/src/utils/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,13 @@ export const config = rc('prime', {
sofaApi: true,
uiDir: defaultUiDir(),
coreUrl: defaultCoreUrl(),
path: defaultCorePath(),
});

config.coreUrl = config.coreUrl.trim().replace(/\/+$/, '');
config.path = `/${config.path.trim()}/`.replace(/\/+$/, '/').replace(/^\/+/, '/');
config.pathClean = config.path.replace(/\/+$/, '');

function defaultUiDir() {
try {
const dir = require.resolve('@primecms/ui/package.json');
Expand Down Expand Up @@ -47,3 +52,15 @@ function defaultCoreUrl() {

return `http://localhost:${PORT || 4000}`;
}

function defaultCorePath() {
const { CORE_PATH } = process.env;
if (CORE_PATH) {
return CORE_PATH;
}
const matches = defaultCoreUrl().match(/[0-9a-zA-Z]\/(.*)$/);
if (matches && matches[1]) {
return matches[1];
}
return '/';
}
5 changes: 3 additions & 2 deletions packages/prime-core/src/utils/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import express from 'express';
import { getRepository } from 'typeorm';
import { Document } from '../entities/Document';
import { Schema } from '../entities/Schema';
import { config } from './config';
import { DocumentTransformer } from './DocumentTransformer';

export const previewRoutes = (app: express.Application) => {
app.get('/prime/redirect', (req, res) => {
app.get(`${config.pathClean}/prime/redirect`, (req, res) => {
const { id, url, accessToken, refreshToken } = req.query;
if (id.length === 36) {
const cookieConfig = {
Expand All @@ -22,7 +23,7 @@ export const previewRoutes = (app: express.Application) => {
res.json({ success: false });
});

app.get('/prime/preview', async (req, res) => {
app.get(`${config.pathClean}/prime/preview`, async (req, res) => {
const cookie = String(req.headers.cookie);
const cookies = cookie.split(';').reduce((acc, item) => {
const [key, value] = item
Expand Down
15 changes: 11 additions & 4 deletions packages/prime-core/src/utils/serveUI.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import express from 'express';
import fs from 'fs';
import path from 'path';
import { config } from './config';
import { log } from './log';

export const serveUI = (app: express.Application, config) => {
export const serveUI = (app: express.Application) => {
const { uiDir } = config;

if (!uiDir) {
log('no ui dir found %o', uiDir);
}

app.use(
config.pathClean,
express.static(uiDir, {
index: false,
})
);

app.get('*', (req, res, next) => {
if (req.url.substr(0, 4) === '/api') {
app.get(`${config.pathClean}*`, (req, res, next) => {
if (req.url.substr(config.path.length, 4) === '/api') {
return next();
}

Expand All @@ -26,7 +28,12 @@ export const serveUI = (app: express.Application, config) => {
log(err);
res.send('error');
} else {
res.send(data.toString().replace('"$PRIME_CONFIG$"', `'${JSON.stringify(config)}'`));
res.send(
data
.toString()
.replace('"$PRIME_CONFIG$"', `'${JSON.stringify(config)}'`)
.replace(/\/static\//g, `${config.path}static/`)
);
}
});
});
Expand Down
4 changes: 2 additions & 2 deletions packages/prime-ui/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { ResetPassword } from './routes/reset-password/ResetPassword';
import { Schemas } from './routes/schemas/Schemas';
import { Settings } from './routes/settings/Settings';
import { Auth } from './stores/auth';
import { ContentTypes } from './stores/contentTypes';
import { Settings as CSettings } from './stores/settings';

const Private = observer(({ children }) => {
if (Auth.isLoggedIn) {
Expand All @@ -38,7 +38,7 @@ export class App extends React.Component {
}

return (
<BrowserRouter>
<BrowserRouter basename={CSettings.path}>
<Route
render={({ location }) => {
let key = location.pathname;
Expand Down
3 changes: 3 additions & 0 deletions packages/prime-ui/src/stores/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,14 @@ const isProd = process.env.NODE_ENV === 'production';

let config = get(window, 'prime.config', '');
let coreUrl = isProd ? '/' : 'http://localhost:4000';
let corePath = '';
const fields: any = [];
let env: any = {};

try {
config = JSON.parse(config);
coreUrl = config.coreUrl || coreUrl;
corePath = config.path || '';
env = config.env || env;
} catch (err) {
if (isProd) {
Expand Down Expand Up @@ -65,6 +67,7 @@ export const Settings = types
.model('Settings', {
isProd,
coreUrl,
path: corePath,
packages: types.array(PackageVersion),
shouldReloadPlayground: false,
env: types.frozen(),
Expand Down