_toDataModelAttribute(type: string, attrName: string, model: ExprModel,
    dataModel: DataModel): void {

    if (attrName === 'id' && type.endsWith('Edge')) {
      let { id } = fromGlobalId(model[attrName]);
      let ids = id.split('---');
      if (dataModel.outID == null) {
        dataModel.outID = ids[0];
      }
      if (dataModel.inID == null) {
        dataModel.outID = ids[1];
      }
      return;
    }

    // All id's treated the same
    if (attrName === 'id' || attrName === 'outID' || attrName === 'inID') {
      invariant(typeof model[attrName] === 'string', 'Error');
      let { id } = fromGlobalId(model[attrName]);
      dataModel[attrName] = new Buffer(id, 'base64');
      return;
    }

    // User specific conversions
    if (type === 'User' && (attrName === 'privateTagId' || attrName === 'tagId')) {
      invariant(typeof model[attrName] === 'string', 'Error');
      let { id } = fromGlobalId(model[attrName]);
      dataModel[attrName] = new Buffer(id, 'base64');
      return;
    }

    dataModel[attrName] = model[attrName];
  }
	mutateAndGetPayload: ({id, categoryId, nameEn, nameCn, washPrice, dryCleanPrice, ironPrice,
		discountWashPrice, discountDryCleanPrice, discountIronPrice, enableWashPriceDiscount,
		enableDryCleanPriceDiscount, enableIronPriceDiscount, special, hideFromUser, enabled}, context, {rootValue}) => {
		const {id: localId} = fromGlobalId(id);

		if (categoryId) {
			const {id: localCategoryId} = fromGlobalId(categoryId);
			categoryId = localCategoryId;
		}

		return processFileUpload('knocknock-laundry', rootValue.request.file)
			.then(upload => Items.update({
				...updateField('sub_category_id', categoryId),
				...updateField('name_en', nameEn),
				...updateField('name_ch', nameCn),
				...updateField('wash_iron_price', washPrice),
				...updateField('dry_clean_price', dryCleanPrice),
				...updateField('iron_price', ironPrice),
				...updateField('discount_wash_iron_price', discountWashPrice),
				...updateField('discount_dry_clean_price', discountDryCleanPrice),
				...updateField('discount_iron_price', discountIronPrice),
				...updateField('have_discount_wash_iron_price', enableWashPriceDiscount),
				...updateField('have_discount_dry_clean_price', enableDryCleanPriceDiscount),
				...updateField('have_discount_iron_price', enableIronPriceDiscount),
				...updateField('special_item', special),
				...updateField('hide_from_user', hideFromUser),
				...(enabled!==undefined)&&{
					disabled: !enabled
				},
				...upload&&{
					image_url: upload.imageUrl
				}
			}, {where:{id: localId}}))
			.then(() => ({localId}));
	}
	mutateAndGetPayload: ({widget}) => {
		// extract numeric widget id from global id
		widget.id = fromGlobalId(widget.id).id;
		// extract numeric owner id from global id
		widget.owner.id = parseInt(fromGlobalId(widget.owner.id).id);
		// save widget with extracted ids
		return updateWidget(widget);		
	},
Example #4
0
 mutateAndGetPayload: ({ poll, user, options }) => {
   const { id: pollHref } = fromGlobalId(poll);
   const { id: userHref } = fromGlobalId(user);
   return new Promise((resolve, reject) => {
     db.createVote(userHref, pollHref, options).then(vote => resolve({
       voteId: vote.id,
       pollHref,
     })).catch(reject);
   });
 },
  mutateAndGetPayload: async ({userId, groupId}) => {
    const localUserId = fromGlobalId(userId).id;
    const localGroupId = fromGlobalId(groupId).id;
    const user = await getItem(userEndpoint, localUserId);
    const groupIndex = user.groups_pending.findIndex(g => g.id == localGroupId);

    user.groups_pending.splice(groupIndex, 1);

    return await updateItem(userEndpoint, localUserId, {
      groups_pending: user.groups_pending,
    }).then(() => {
      return { localUserId, localGroupId };
    });
  },
Example #6
0
 (globalId) => {
     var {type, id} = fromGlobalId(globalId);
     return {
         type: type,
         id:   id
     };
 },
Example #7
0
 (globalId) => {
   let {type} = fromGlobalId(globalId);
   if (type === 'Store') {
     return store
   }
   return null;
 },
 mutateAndGetPayload: ( {id}, context, { rootValue: objectManager } ) =>
 {
   var local_id = fromGlobalId(id).id;
   return objectManager.remove( 'Translaticiarum', { id: local_id} )
   .then( ( ) => ( {id} ) )
   ;
 }
Example #9
0
export function objectIdFromData(data) {
  if (Types.ObjectId.isValid(data.toString())) {
    return new Types.ObjectId(data.toString());
  }

  return new Types.ObjectId(fromGlobalId(data).id.toString());
}
Example #10
0
async function mutate(
  type: string,
  op: MutationType,
  mutationArgs: InnerMutationArgs,
  options: MutationOptions,
  story: StoryT
): Promise<InnerMutationResult> {
  const { id: globalId, parentId: globalParentId, attrs } = mutationArgs;
  const localId =
    op !== 'CREATE' && !options.fSingleton ? fromGlobalId(globalId).id : null;
  const parentNode = getNodeFromGlobalId(globalParentId);
  const result: InnerMutationResult = {
    globalId,
    localId,
    globalParentId,
    parentNode,
    node: null,
  };
  let newAttrs: any = attrs;
  newAttrs = resolveGlobalIds(newAttrs, options.globalIds);
  if (op === 'CREATE') {
    result.node = await db[`create${type}`](newAttrs, { story });
    result.localId = result.node.id;
  } else {
    /* UPDATE */
    result.node = options.fSingleton
      ? await db[`update${type}`](newAttrs, { story })
      : await db[`update${type}`](localId, newAttrs, { story });
  }
  result.node = addTypeAttr(result.node, type);
  return result;
}
Example #11
0
 mutateAndGetPayload: ({text, id}) => {
   // important, else it would be encoded client id,
   // then database don't know how to handle
   var localThreadId = fromGlobalId(id).id;
   var {messageID, threadID} = addMessage(text, localThreadId);
   return {messageID, threadID};
 }
Example #12
0
 (globalId) => {
   const { type, id } = fromGlobalId(globalId);
   if (type === 'HackerNewsV2User') {
     return getUser(id);
   }
   return getItem(id);
 },
	mutateAndGetPayload: ({id, nameEn, nameCn}) => {
		const {id: localId} = fromGlobalId(id);
		return SubCategories.update({
			...updateField('name_en', nameEn),
			...updateField('name_ch', nameCn)
		}, {where:{id:localId}}).then(() => ({localId}));
	}
	mutateAndGetPayload: ({id}, {userId}) => {
		const {id: dbId} = fromGlobalId(id);
		return UserAddresses.destroy({where:{$and:{
				user_id: userId,
				id: dbId
			}}}).then(() => ({userId, addressId: id}))
	}
	mutateAndGetPayload: ({user}) => {
		// extract numeric widget id from global id
		user.id = fromGlobalId(user.id).id;
		// extract numeric owner id from global id
		// save widget with extracted ids
		return updateUserFromUser(user);
	},
Example #16
0
const resolveGlobalIds = (
  prevAttrs: Object,
  globalIds: Array<string> = []
): Object => {
  let attrs = prevAttrs;
  if (attrs == null || !globalIds.length) return attrs;
  for (let i = 0; i < globalIds.length; i++) {
    const locatorPath = globalIds[i];
    const tokens = locatorPath.split('.');
    const curToken = tokens[0];
    if (tokens.length === 1) {
      const globalId = attrs[curToken];
      if (globalId == null) continue;
      attrs = timmSet(attrs, curToken, fromGlobalId(globalId).id);
    } else {
      const subLocatorPath = tokens.slice(1).join('.');
      if (curToken === '*') {
        for (let idx = 0; idx < attrs.length; idx++) {
          attrs = timmSet(
            attrs,
            idx,
            resolveGlobalIds(attrs[idx], [subLocatorPath])
          );
        }
      } else {
        attrs = timmSet(
          attrs,
          curToken,
          resolveGlobalIds(attrs[curToken], [subLocatorPath])
        );
      }
    }
  }
  return attrs;
};
Example #17
0
 (globalId) => {
     let {type} = fromGlobalId(globalId);
     if (type === "Store") {
         return store;
     }
     return null;
 },
 (globalId, context) => {
   if(globalId === VIEWER_ID)
     return VIEWER_BODY;
   const {type, id} = fromGlobalId(globalId);
   const getById = prepareTypeInfo().getByIdByGraphqlTypeName[type];
   return getById ? getById(context, id) : null;
 },
 mutateAndGetPayload: ( {id}, { rootValue: {user_id} } ) =>
 {
   var localTranslaticiarumId = fromGlobalId(id).id;
   return DA_Translaticiarum_delete( user_id, localTranslaticiarumId )
   .then( ( ) => ( {id} ) )
   ;
 }
  mutateAndGetPayload: async({ id }, context, { rootValue: objectManager }) => {
    const local_id = fromGlobalId( id ).id

    await objectManager.remove( 'ToDo', { id: local_id })

    return { id }
  },
			.then(upload => {
				if (!upload) throw 'Upload file failed';

				const {id: localCategoryId} = fromGlobalId(categoryId);

				return Items.create({
					sub_category_id: localCategoryId,
					name_en: nameEn,
					name_ch: nameCn,
					wash_iron_price: washPrice,
					dry_clean_price: dryCleanPrice,
					iron_price: ironPrice,
					discount_wash_iron_price: discountWashPrice,
					discount_dry_clean_price: discountDryCleanPrice,
					discount_iron_price: discountIronPrice,
					have_discount_wash_iron_price: enableWashPriceDiscount,
					have_discount_dry_clean_price: enableDryCleanPriceDiscount,
					have_discount_iron_price: enableIronPriceDiscount,
					special_item: special,
					hide_from_user: hideFromUser,
					...(enabled!==undefined)&&{
						disabled: !enabled
					},
					image_url: upload.imageUrl,
					created_on: new Date().toString()
				});
			})
var nodeDefinitions = GraphQLRelay.nodeDefinitions(function(globalId) {
  var idInfo = GraphQLRelay.fromGlobalId(globalId)
  if (idInfo.type == 'Image') {
    return getImage(idInfo.id)
  }
  return null
})
Example #23
0
 mutateAndGetPayload: ({ updatedUser }) => {
   const update = updatedUser;
   const id = update.id;
   delete update.id;
   const { id: href } = fromGlobalId(id);
   return db.updateUser(href, update);
 },
  mutateAndGetPayload: async ({id, attributes}) => {
    const localGroupId = fromGlobalId(id).id;

    return await updateItem(groupEndpoint, localGroupId, attributes)
      .then(result => {
        return {localGroupId: result.id};
      });
  },
 .then((res) => {
   expect(res).to.have.status(200);
   res = res.body.data;
   expect(res.viewer.sites.totalCount).to.equal(3);
   expect(res.viewer.sites.edges.length).to.be.above(0);
   expect(fromGlobalId(res.viewer.sites.edges[0].node.id).id).to.equal('3');
   expect(res.viewer.sites.pageInfo.hasNextPage).to.be.true;
 });
Example #26
0
 (globalId) => {
   var {type, id} = fromGlobalId(globalId);
   if (type === 'User') {
     return getUser(id);
   } else {
     return null;
   }
 },
Example #27
0
 (globalId) => {
     var {type, id} = fromGlobalId(globalId);
     console.log('globalId: ' + globalId + " id value: " + id + " and type value: " + type);
     if(type === 'User')
         return  User.getUserById(id);
     return 'null';
     //TODO: more to come here items feeds, login
 },
Example #28
0
 mutateAndGetPayload: ({ pollId }) => {
   const { id: href } = fromGlobalId(pollId);
   return new Promise((resolve, reject) => {
     db.deletePoll(href)
       .then(() => resolve({ pollId }))
       .catch(reject);
   });
 },
Example #29
0
 (globalId) => {
   var {type, id} = fromGlobalId(globalId);
   if (type === 'Card') {
     return getCard(id);
   } else {
     return null;
   }
 },
	mutateAndGetPayload: ({id, express, note, statusId, pickupDate,
		pickupTime, pickupAddress, pickupWorkerId, factoryId, toPayPrice, orderItems}) => {
		const {id: localId} = fromGlobalId(id);
		
		if (pickupWorkerId) {
			const {id: localWorkerId} = fromGlobalId(pickupWorkerId);
			pickupWorkerId = localWorkerId;
		}
		if (statusId) {
			const {id: localStatusId} = fromGlobalId(statusId);
			statusId = localStatusId;
		}
		if (factoryId) {
			const {id: localFactoryId} = fromGlobalId(factoryId);
			factoryId = localFactoryId;
		}

		return Orders.update({
			...updateField('express_order', express),
			...updateField('description', note),
			...updateField('order_status_id', statusId),
			...updateField('pickup_date', pickupDate),
			...updateField('pickup_time', pickupTime),
			...updateField('pickup_address', pickupAddress),
			...updateField('pickup_worker_id', pickupWorkerId),
			...updateField('factory_id', factoryId),
			...updateField('to_pay_price', toPayPrice)
		}, {where:{id: localId}}).then(() => {
			if (orderItems) {
				return OrderDetails.destroy({where:{order_id: localId}})
					.then(() => {
						if (orderItems.length > 0) {
							return prepareOrderItems(localId, orderItems)
								.then(items => OrderDetails.bulkCreate(items))
								.then(() => localId);
						} else {
							return localId;
						}
					})
					.then(localId => ({localId}));
			} else {
				return {localId};
			}
		});
	}