def extract_value_from_input(input, field_id, model_type, model): """ BBB: metodo utilizzato ampiamente nelle mutation per controllare gli ID che vengono ricevuti dal front-end. """ settingID = input.get(field_id, None) if not settingID: return None try: settingID = int(settingID) except ValueError: try: _type, settingID = Node.from_global_id(settingID) assert _type == model_type, \ u"Expected a {0} object, found {1}".format(model_type, _type) except Exception: raise Exception( u"Received wrong id for querying the db. " u"{0}: {1}".format(field_id, settingID)) try: return model.objects.get(id=settingID) except ObjectDoesNotExist: raise Exception( u"Non esiste nessun Wsp con questo id nel database. " u"{0}: {1}".format(field_id, settingID))
def resolve_document(root, info, id): _, id = Node.from_global_id(id) doc = DocumentModel.objects(id=id).first() if doc is not None: if access_to_document(doc): return doc else: raise GraphQLError("You do not have access to this document.") else: return None
def mutate(root, info, **kwargs): _id = kwargs.pop('id') _, user_id = Node.from_global_id(_id) user = models.User.objects.get(pk=user_id) user.__dict__.update(**kwargs) if 'password' in kwargs: user.set_password(kwargs['password']) user.save() ok = True return UpdateUser(user=user, ok=ok)
def get_node_from_global_id(cls, info, global_id, only_type=None): try: _type, _id = Node.from_global_id(global_id) graphene_type = info.schema.get_type(_type).graphene_type except Exception as e: return None if only_type: assert graphene_type == only_type, ( "Must receive a {} id.").format(only_type._meta.name) # We make sure the ObjectType implements the "Node" interface if cls.__base__ not in graphene_type._meta.interfaces: return None return _id
def mutate(self, cls, input, context, info): id = input.get("id") try: id = int(id) except ValueError: try: _type, id = Node.from_global_id(input.get("id")) assert _type == 'ProjectNode', 'Found {} instead of project'.format( _type) id = int(id) except: raise Exception("Received Invalid Project id: {}".format(id)) project = Project._meta.model.objects.get(id=id) if project is not None: project.delete() return DeleteProject(project=project)
def mutate_and_get_payload(cls, input, info): name = input.get('name') homeworld_id = input.get('homeworld_id') try: homeworld_id = int(homeworld_id) except ValueError: try: _type, homeworld_id = Node.from_global_id(homeworld_id) assert _type == 'planet', 'The homeworld should be a Planet, but found {}'.format(resolved.type) except: raise Exception("Received wrong Planet id: {}".format(homeworld_id)) homeworld = Planet._meta.model.objects.get(id=homeworld_id) hero = Hero._meta.model(name=name, homeworld=homeworld) hero.save() return CreateHero(hero=hero, ok=bool(hero.id))
def resolver(self, args, context, info, session): query = query_class(session) filters = args.get('filters') if filters: typed = filter_to_internal.cast_from(filters) criteria = tuple(query.criteria_from_dict(typed)) query.filter(*criteria) filtered_count = len(query) order_by = args.get('orderBy') if order_by: order_by_values = OrderedDict(_parse_order_by(order_by)) mapped = order_by_to_mapped.cast_from(order_by_values) # TODO only add this sort by id if there is no other sort by a unique field # required in order have stable sorting and paging when sorting by a non-unique field mapped['_id'] = True criteria = tuple(query.sort_criteria_from_dict(mapped)) query.order_by(*criteria) offset = 0 after = args.get('after') if after: offset = int(Node.from_global_id(after)[1]) query.offset(offset) offset += 1 args.pop('after') first = args.get('first') if first: limit = int(first) query.limit(limit) instances = list(query.collection()) context['count'] = filtered_count context['pageInfo'] = PageInfo( start_cursor=offset_to_cursor(query.start_index), end_cursor=offset_to_cursor(query.end_index), has_previous_page=False if query.start_index is None else query.start_index > 0, has_next_page=False if query.end_index is None else query.end_index < filtered_count - 1) return instances
def mutate(self, args, context, info): name = args.get('name') homeworld_id = args.get('homeworld_id') try: homeworld_id = int(homeworld_id) except ValueError: try: _type, homeworld_id = Node.from_global_id(homeworld_id) assert _type == 'planet', 'The homeworld should be a Planet, but found {}'.format( resolved.type) except: raise Exception( "Received wrong Planet id: {}".format(homeworld_id)) homeworld = Planet._meta.model.objects.get(id=homeworld_id) hero = Hero._meta.model(name=name, homeworld=homeworld) hero.save() return CreateHero(hero=hero, ok=bool(hero.id))
def mutate(self, cls, input, context, info): id = input.get("id") try: id = int(id) except ValueError: try: _type, id = Node.from_global_id(input.get("id")) assert _type == 'DeveloperNode', 'Found {} instead of developer'.format( _type) id = int(id) except: raise Exception("Received Invalid Developer id: {}".format(id)) developer = Developer._meta.model.objects.get(id=id) user_id = input.get("user_id") if user_id is not None: developer.user_id = user_id developer.save() return UpdateDeveloper(developer=developer)
def mutate_and_get_payload(self, info, name, homeworld_id, client_id_mutation=None): try: homeworld_id = int(homeworld_id) except ValueError: try: _type, homeworld_id = Node.from_global_id(homeworld_id) assert _type == 'planet', 'The homeworld should be a Planet, but found {}'.format( resolved.type) except: raise Exception( "Received wrong Planet id: {}".format(homeworld_id)) homeworld = Planet._meta.model.objects.get(id=homeworld_id) hero = Hero._meta.model(name=name, homeworld=homeworld) hero.save() return CreateHero(hero=hero, ok=bool(hero.id))
def mutate_and_get_payload(cls, input, context, info): name = input.get('name') summary = input.get('summary') developers = input.get("developers") try: developers = list(developers) except ValueError: try: for developer_id in developers: _type, developers = Node.from_global_id( input.get("developer_id")) assert _type == 'DeveloperNode', 'Found {} instead of developer'.format( _type) developers = list(developers) except: raise Exception( "Received Invalid Developer id: {}".format(developer_id)) project = Project(name=name, summary=summary) project.save() for developer_id in developers: developer = Developer._meta.model.objects.get(id=developer_id) project.developers.add(developer) project.developers = project.developers.all() return CreateProject(project=project)
def resolve_user_update(root, info, id): _, id = Node.from_global_id(id) return rx.Observable.create(user_update_on_subscribe(root, info, id))
def resolve_user(root, info, id): _, id = Node.from_global_id(id) return UserModel.objects(id=id).first()
def test_replace_offer_items_by_sku( get_product_by_sku_m, app, order, product_dict_1, product_dict_2, product_dict_4, master_product_1, master_product_2, master_product_4, product_1_review_1, product_1_review_2, product_1_review_3_zero_score, product_2_review_1, source_1, shipping_rate_3, salestax_rate, theme_1, theme_2, theme_3, graphql_client_admin, ): master_product1_id = master_product_1.id master_product2_id = master_product_2.id master_product4_id = master_product_4.id products = [ [product_dict_4, product_dict_4, product_dict_4, product_dict_4], ] create_product_offers(order.id, products) db.session.commit() offer_items = db.session.query( OfferItem ).join( OfferItem.product_offer ).order_by( OfferItem.id.asc() ).all() assert len(offer_items) == 4 assert offer_items[0].name == 'wine_name4' assert offer_items[0].sku == 'sku4' assert offer_items[0].master_product_id == master_product4_id assert offer_items[0].score_num == 88 assert offer_items[0].image == 'img_url' assert offer_items[0].description == 'short_desc' assert offer_items[0].location == 'region' assert offer_items[0].highlights == ['highlight1', 'highlight2'] assert offer_items[0].varietals == ['varietals'] assert offer_items[0].prof_reviews == [] assert offer_items[0].qty is None assert offer_items[0].price == Decimal('19.99') assert offer_items[0].brand == 'brand' assert offer_items[0].qoh == 1 assert offer_items[0].msrp == Decimal('21.99') assert offer_items[0].product_url == 'http://product' assert offer_items[0].best_theme_id == theme_1.id _assert_offer_items_are_same(offer_items, 1, 0) _assert_offer_items_are_same(offer_items, 2, 0) _assert_offer_items_are_same(offer_items, 3, 0) product_offer1 = offer_items[0].product_offer assert product_offer1.order_id == order.id assert product_offer1.source_id == source_1.id assert product_offer1.bottle_qty == 4 assert product_offer1.total_cost == Decimal('112.36') assert product_offer1.priority == 1 assert product_offer1.name == 'source_1' assert product_offer1.salestax_rate == Decimal('0.0925') assert product_offer1.shipping_cost == Decimal('25') assert product_offer1.salestax_cost == Decimal('7.40') assert product_offer1.product_cost == Decimal('79.96') query = ''' mutation($input: SaveOrderInput!) { saveOrder(input: $input) { clientMutationId order { productOffers { edges { node { priority name wineType bottleQty productCost salestaxCost shippingCost totalCost offerItems { edges { node { id brand name scoreNum image description location qty sku qoh productUrl price msrp highlights varietals topProductReview { reviewerName reviewScore } productReviews { reviewerName reviewScore } bestTheme { title}}}}}}}}}} ''' def get_product_by_sku_mock(sku): if sku == product_dict_1['sku']: return product_dict_1 if sku == product_dict_2['sku']: return product_dict_2 return None get_product_by_sku_m.side_effect = get_product_by_sku_mock # Test res = graphql_client_admin.post(query, variables={ 'input': { 'clientMutationId': 'replace by sku test', 'id': Node.to_global_id('Order', order.id), 'offerItemReplacements': [ { 'offerItemId': Node.to_global_id('OfferItem', offer_items[3].id), 'newBestThemeId': Node.to_global_id('Theme', theme_3.id), }, { 'offerItemId': Node.to_global_id('OfferItem', offer_items[0].id), 'newSku': product_dict_2['sku'], }, { 'offerItemId': Node.to_global_id('OfferItem', offer_items[1].id), 'newSku': product_dict_1['sku'], 'newBestThemeId': Node.to_global_id('Theme', theme_2.id), }, ], } }) # Sort offer items for test stability (sorting is not always the same in response for some reason) res_offer_items = res.get('data', {}).get('saveOrder', {}).get( 'order', {} ).get('productOffers', {}).get('edges', [{}])[0].get('node', {}).get('offerItems', {}) res_offer_item_edges = res_offer_items.get('edges') if res_offer_item_edges: res_offer_item_edges = sorted( res_offer_item_edges, key=lambda n1: int(Node.from_global_id(n1['node']['id'])[1]) ) for n2 in res_offer_item_edges: del n2['node']['id'] res_offer_items['edges'] = res_offer_item_edges # Check expected = {'data': {'saveOrder': { 'clientMutationId': 'replace by sku test', 'order': {'productOffers': {'edges': [ {'node': { 'bottleQty': 4, 'name': 'source_1', 'offerItems': {'edges': [ {'node': {'bestTheme': {'title': 'theme 1'}, 'brand': 'brand', 'description': 'short_desc', 'highlights': ['highlight1', 'highlight2'], 'image': 'img_url', 'location': 'region', 'msrp': '21.99', 'name': 'wine_name4', 'price': '19.99', 'productUrl': 'http://product', 'qoh': 1, 'qty': None, 'scoreNum': 88, 'sku': 'sku4', 'topProductReview': None, 'productReviews': [], 'varietals': ['varietals']}}, {'node': {'bestTheme': {'title': 'theme 3'}, 'brand': 'brand', 'description': 'short_desc', 'highlights': ['highlight1', 'highlight2'], 'image': 'img_url', 'location': 'region', 'msrp': '21.99', 'name': 'wine_name4', 'price': '19.99', 'productUrl': 'http://product', 'qoh': 1, 'qty': None, 'scoreNum': 88, 'sku': 'sku4', 'topProductReview': None, 'productReviews': [], 'varietals': ['varietals']}}, {'node': {'bestTheme': {'title': 'theme 1'}, 'brand': 'brand', 'description': 'short_desc', 'highlights': ['highlight1', 'highlight2'], 'image': 'img_url', 'location': 'region', 'msrp': '3.99', 'name': 'wine_name2', 'price': '11.00', 'productUrl': 'http://product', 'qoh': 1, 'qty': None, 'scoreNum': 89, 'sku': 'sku2', 'topProductReview': {'reviewScore': 78, 'reviewerName': 'reviewer 2 1'}, 'productReviews': [{'reviewScore': 78, 'reviewerName': 'reviewer 2 1'}], 'varietals': ['varietals']}}, {'node': {'bestTheme': {'title': 'theme 2'}, 'brand': 'brand', 'description': 'short_desc', 'highlights': ['highlight1', 'highlight2'], 'image': 'img_url', 'location': 'region', 'msrp': '3.99', 'name': 'wine_name1', 'price': '10.00', 'productUrl': 'http://product', 'qoh': 1, 'qty': None, 'scoreNum': 90, 'sku': 'sku1', 'topProductReview': {'reviewScore': 90, 'reviewerName': 'reviewer 1 2'}, 'productReviews': [{'reviewScore': 90, 'reviewerName': 'reviewer 1 2'}, {'reviewScore': 80, 'reviewerName': 'reviewer 1 1'}], 'varietals': ['varietals']}}]}, 'priority': 1, 'productCost': '60.98', 'salestaxCost': '5.64', 'shippingCost': '25.00', 'totalCost': '91.62', 'wineType': 'mixed'}}]}}}}} assert res == expected get_product_by_sku_m.assert_has_calls([ call('sku2'), call('sku1'), ]) assert get_product_by_sku_m.call_count == 2 offer_items = db.session.query( OfferItem ).join( OfferItem.product_offer ).order_by( OfferItem.id.asc() ).all() assert len(offer_items) == 4 assert offer_items[0].name == 'wine_name4' assert offer_items[0].sku == 'sku4' assert offer_items[0].master_product_id == master_product4_id assert offer_items[0].score_num == 88 assert offer_items[0].image == 'img_url' assert offer_items[0].description == 'short_desc' assert offer_items[0].location == 'region' assert offer_items[0].highlights == ['highlight1', 'highlight2'] assert offer_items[0].varietals == ['varietals'] assert offer_items[0].prof_reviews == [] assert offer_items[0].qty is None assert offer_items[0].price == Decimal('19.99') assert offer_items[0].brand == 'brand' assert offer_items[0].qoh == 1 assert offer_items[0].msrp == Decimal('21.99') assert offer_items[0].product_url == 'http://product' assert offer_items[0].best_theme_id == theme_1.id assert offer_items[1].name == 'wine_name4' assert offer_items[1].sku == 'sku4' assert offer_items[1].master_product_id == master_product4_id assert offer_items[1].score_num == 88 assert offer_items[1].image == 'img_url' assert offer_items[1].description == 'short_desc' assert offer_items[1].location == 'region' assert offer_items[1].highlights == ['highlight1', 'highlight2'] assert offer_items[1].varietals == ['varietals'] assert offer_items[1].prof_reviews == [] assert offer_items[1].qty is None assert offer_items[1].price == Decimal('19.99') assert offer_items[1].brand == 'brand' assert offer_items[1].qoh == 1 assert offer_items[1].msrp == Decimal('21.99') assert offer_items[1].product_url == 'http://product' assert offer_items[1].best_theme_id == theme_3.id assert offer_items[2].name == 'wine_name2' assert offer_items[2].sku == 'sku2' assert offer_items[2].master_product_id == master_product2_id assert offer_items[2].score_num == 89 assert offer_items[2].image == 'img_url' assert offer_items[2].description == 'short_desc' assert offer_items[2].location == 'region' assert offer_items[2].highlights == ['highlight1', 'highlight2'] assert offer_items[2].varietals == ['varietals'] assert offer_items[2].prof_reviews == [{'name': 'reviewer 2 1', 'score': 78}] assert offer_items[2].qty is None assert offer_items[2].price == Decimal('11') assert offer_items[2].brand == 'brand' assert offer_items[2].qoh == 1 assert offer_items[2].msrp == Decimal('3.99') assert offer_items[2].product_url == 'http://product' assert offer_items[2].best_theme_id == theme_1.id assert offer_items[3].name == 'wine_name1' assert offer_items[3].sku == 'sku1' assert offer_items[3].master_product_id == master_product1_id assert offer_items[3].score_num == 90 assert offer_items[3].image == 'img_url' assert offer_items[3].description == 'short_desc' assert offer_items[3].location == 'region' assert offer_items[3].highlights == ['highlight1', 'highlight2'] assert offer_items[3].varietals == ['varietals'] assert offer_items[3].prof_reviews == [{'name': 'reviewer 1 2', 'score': 90}, {'name': 'reviewer 1 1', 'score': 80}] assert offer_items[3].qty is None assert offer_items[3].price == Decimal('10') assert offer_items[3].brand == 'brand' assert offer_items[3].qoh == 1 assert offer_items[3].msrp == Decimal('3.99') assert offer_items[3].product_url == 'http://product' assert offer_items[3].best_theme_id == theme_2.id product_offer1 = offer_items[0].product_offer assert product_offer1.order_id == order.id assert product_offer1.source_id == source_1.id assert product_offer1.bottle_qty == 4 assert product_offer1.total_cost == Decimal('91.62') assert product_offer1.priority == 1 assert product_offer1.name == 'source_1' assert product_offer1.salestax_rate == Decimal('0.0925') assert product_offer1.shipping_cost == Decimal('25') assert product_offer1.salestax_cost == Decimal('5.64') assert product_offer1.product_cost == Decimal('60.98')
def new_mutate(*args, **kwargs): if "id" in kwargs: kwargs["id"] = Node.from_global_id(kwargs["id"])[1] return old_mutate(*args, **kwargs)