Skip to content

Instantly share code, notes, and snippets.

@gaupoit
Created May 18, 2021 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gaupoit/cbdfe5547d1bc5127a6e955396eb3d9b to your computer and use it in GitHub Desktop.
Save gaupoit/cbdfe5547d1bc5127a6e955396eb3d9b to your computer and use it in GitHub Desktop.
Poor performance
onst apiResponse = require('./tool/api-response');
const MESSAGE = require('./message/messages');
const UPDATE_OWNERSHIP = 'updateOwnership';
const PLANT = 'Plant';
const USER_TABLE = '_User';
const PLANT_FIELD = 'plant';
const PLANT_OWNERSHIP = 'PlantOwnership';
const OWNERSHIP_ROLE_FIELD = 'ownershipRole';
const OBJECT_ID = 'objectId';
const OWNERSHIP_ROLE = 'OwnershipRole';
const OWNER_FIELD = 'owner';
const FUNCTION_GROUP_FARM_PLANT_OWNERSHIP = 'groupFarmPlantOwnership';
const FARM_FIELD = 'farm';
const DEFAULT_LIMIT = 20;
const DEFAULT_SKIP = 0;
const NAME_FIELD = 'name';
const IS_REMOVE_FIELD = 'isRemove';
const FARM = 'Farm';
const FARM_TABLE = Parse.Object.extend(FARM);
const PLANT_OWNERSHIP_TABLE = Parse.Object.extend(PLANT_OWNERSHIP);
const OWNER_ROLE = 'Owner';
const MASTER_OWNER_ROLE = 'MasterOwner'
const STATUS_CODE_OK =200;
const STATUS_CODE_NOT_FOUND = 404;
const STATUS_CODE_FORBIDDEN = 403;
/**
* Function group farm of plant ownership.
* @param {object} request(ownerId: String, limit: int, skip: int, withCount: boolean)
* @return {Array}
*/
Parse.Cloud.define(FUNCTION_GROUP_FARM_PLANT_OWNERSHIP, async function(request) {
const {ownerId, limit, skip, withCount} = request.params;
// Document: https://docs.parseplatform.org/js/guide/#aggregate
// Using aggregate to colapse unique objectId.
const pipeline = [
{match: {owner: ownerId, isRemove: false}},
{group: {objectId: `$${FARM_FIELD}`}},
];
const query = new Parse.Query(PLANT_OWNERSHIP_TABLE);
const farmQuery = new Parse.Query(FARM_TABLE);
query.limit(limit? limit: DEFAULT_LIMIT);
query.skip(skip ? skip : DEFAULT_SKIP);
if (withCount) query.withCount();
const resultsAggregate = await query.aggregate(pipeline, {useMasterKey: true});
// !!x.objectId will not return null data
const farmCreativeQuery = await farmQuery.equalTo(OWNER_FIELD, convertToPointer(USER_TABLE, ownerId)).find();
const farmAssign = resultsAggregate.filter((x)=> !!x.objectId);
const farmCreative = await farmCreativeQuery.map(function(x) {
return {objectId: x.id};
});
const farm = farmAssign.concat(farmCreative).reduce((unique, o) => {
if (!unique.some((obj) => obj.objectId === o.objectId && obj.value === o.value)) {
unique.push(o);
}
return unique;
}, []);
return farm;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment