Skip to content

Instantly share code, notes, and snippets.

@dplewis
Created January 8, 2021 23:31
Show Gist options
  • Save dplewis/3e911af29a667a88b9f92fa007e735e2 to your computer and use it in GitHub Desktop.
Save dplewis/3e911af29a667a88b9f92fa007e735e2 to your computer and use it in GitHub Desktop.
const Config = require('./Config');
const Auth = require('./Auth');
const RESTController = require('parse/lib/node/RESTController');
const URL = require('url');
const Parse = require('parse/node');
function getIPAddress() {
var interfaces = require('os').networkInterfaces();
for (var devName in interfaces) {
var iface = interfaces[devName];
for (var i = 0; i < iface.length; i++) {
var alias = iface[i];
if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal)
return alias.address;
}
}
return '0.0.0.0';
}
function getAuth({ installationId, sessionToken, useMasterKey }, config) {
installationId = installationId || 'cloud';
if (useMasterKey) {
return Promise.resolve(new Auth.Auth({ config, isMaster: true, installationId }));
}
if (sessionToken) {
return Auth.getAuthForSessionToken({
config,
sessionToken,
installationId,
});
} else {
return Promise.resolve(new Auth.Auth({ config, installationId }));
}
}
function ParseServerRESTController(applicationId, router) {
async function handleRequest(method, path, data = {}, options = {}, config) {
// Store the arguments, for later use if internal fails
const args = arguments;
if (!config) {
config = Config.get(applicationId);
}
config.ip = config.ip || getIPAddress();
config.headers = config.headers || {};
const serverURL = URL.parse(config.serverURL);
if (path.indexOf(serverURL.path) === 0) {
path = path.slice(serverURL.path.length, path.length);
}
if (path[0] !== '/') {
path = '/' + path;
}
if (path === '/batch') {
if (data.transaction === true) {
await config.database.createTransactionalSession();
}
const promises = data.requests.map(request => {
return handleRequest(request.method, request.path, request.body, options, config).then(
response => {
if (options.returnStatus) {
const status = response._status;
delete response._status;
return { success: response, _status: status };
}
return { success: response };
},
error => {
return {
error: { code: error.code, error: error.message },
};
}
);
});
const result = await Promise.all(promises);
if (data.transaction === true) {
if (result.find(resultItem => typeof resultItem.error === 'object')) {
await config.database.abortTransactionalSession();
throw result;
} else {
await config.database.commitTransactionalSession();
return result;
}
} else {
return result;
}
}
let query;
if (method === 'GET') {
query = data;
}
let installationId = options.installationId;
if (!(installationId && typeof installationId === 'string')) {
const installationController = Parse.CoreManager.getInstallationController();
installationId = await installationController.currentInstallationId();
}
const userController = Parse.CoreManager.getUserController();
let sessionToken;
if (options && typeof options.sessionToken === 'string') {
sessionToken = options.sessionToken;
} else if (userController) {
const user = await userController.currentUserAsync();
if (user) {
sessionToken = user.getSessionToken();
}
}
const info = {
applicationId: applicationId,
sessionToken,
installationId,
useMasterKey: options.useMasterKey,
context: options.context || {},
}
const auth = await getAuth(info, config);
const request = {
body: data,
config,
auth,
info,
query,
};
try {
const resp = await router.tryRouteRequest(method, path, request);
const { response, status } = resp;
if (options.returnStatus) {
return { ...response, _status: status };
} else {
return response;
}
} catch (err) {
if (
err instanceof Parse.Error &&
err.code == Parse.Error.INVALID_JSON &&
err.message == `cannot route ${method} ${path}`
) {
return RESTController.request.apply(null, args);
} else {
throw err;
}
}
}
return {
request: handleRequest,
ajax: RESTController.ajax,
handleError: RESTController.handleError,
};
}
export default ParseServerRESTController;
export { ParseServerRESTController };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment