Ejemplo n.º 1
0
 .then(({ json, response }) => {
     //xdebug ("retrieve:", json);
     if (!response.ok) {
         throw new Error ("fetch() error: "+response.statusText+", ret="+JSON.stringify(json));
     }
     if (response.ok && (!json.errcode || json.errcode == 0)) {
         // must be a array.
         var total = json.count;
         const camelizedJson = camelizeKeys(json.data)
         //const nextPageUrl = getNextPageUrl(response)
         const res = normalize(camelizedJson, Schemas.ORDER_ARRAY);
         xdebug ("retrieveMyLuckyOrders:", res);
         dispatch(retrieveMyLuckyOrderSuccess({db:res.entities.orders, total, page, result: res.result }));
         return {db:res.entities.orders, total, page, result: res.result };
     } else {
         throw new Error ("server errcode="+json.errcode + ", message="+json.message);
     }
 })
Ejemplo n.º 2
0
    fetch(`${config.baseUrl}/companies`).then((jsonData) => {
      const response = normalize(jsonData, [company]);

      dispatch({
        type: types.FILL_EMPLOYEES,
        payload: {
          employeesMap: response.entities.employees,
        }
      });

      dispatch({
        type: types.FILL_COMPANIES,
        payload: {
          companyIds: response.result,
          companyMap: response.entities.companies
        }
      });
    });
export default store => next => action => {
  if(!shouldNormalizeAction(action)) return next(action);

  const data = action.payload.data;
  const schema = action.meta.previousAction.normalize.schema;
  const path = get(action.meta.previousAction.normalize, 'path');

  const requestData = path ? get(data, path) : data;
  const normalizedData = normalize(requestData, schema);
  const normalizedDataWithAllIds = appendAllIds(normalizedData);
  return next({
    ...action,
    payload: {
      ...action.payload,
      data: normalizedDataWithAllIds,
    }
  });
};
Ejemplo n.º 4
0
  doAction: function* fetchModelSaga({
    schema,
    filter,
    sort,
    direction,
    cursor,
    llClient,
    first,
    last
  }) {
    const plainFilter = Iterable.isIterable(filter) ? filter.toJS() : filter;
    const plainSort = Iterable.isIterable(sort) ? sort.toJS() : sort;
    const plainCursor = Iterable.isIterable(cursor) ? cursor.toJS() : cursor;

    const schemaClass = schemas[schema];
    const { status, body } = yield call(llClient.getConnection, {
      schema,
      filter: plainFilter,
      sort: plainSort,
      cursor: plainCursor,
      first,
      last
    });

    if (status === 401) {
      throw new Unauthorised('Unauthorised');
    }
    if (status >= 300) {
      throw new HttpError(body.message || body, { status });
    }

    const models = map(body.edges, 'node');
    const ids = map(models, '_id');
    const edges = map(body.edges, item => (new OrderedMap({ id: item.node._id, cursor: item.cursor })));
    const normalizedModels = normalize(models, arrayOf(schemaClass));
    const entities = entityReviver(normalizedModels);
    const pageInfo = fromJS(body.pageInfo);

    // put all of the models into the master record in the model store
    yield put(mergeEntitiesDuck.actions.mergeEntitiesAction(entities));

    // map the ids against the filter in the pagination store
    return yield { schema, filter, sort, cursor, direction, edges, pageInfo, ids };
  }
Ejemplo n.º 5
0
/**
 * A function that normalizes data based on specified model relationships using
 * normalizr.
 *
 * This will map over the provided models and pass in a normalizr schema containing
 * each models schema. If the entities from the response that match the model are
 * an array, the schema will be wrapped in arrayOf().
 */
export default ({data, modelFunctions, clientState}: NormalizationParameters): NormalizedData | Object => {
	const {models} = clientState

	/* Create a map of ModelFunctions who's keys match
	 * those of the Data result
	 * */
	const keyedFunctions: {[key:string]: ModelFunction} = _.mapKeys(modelFunctions,
		(modelFunction: ModelFunction) =>
			modelFunction.fieldName)

	if (!data) return {}
	return normalize(data, _.mapValues(keyedFunctions, (modelFunction: ModelFunction) => {
		const entities = data[modelFunction.fieldName]
		const modelData: ModelDataType = models[modelFunction.modelName]

		if (Array.isArray(entities)) return arrayOf(modelData.normalizrSchema)
		return modelData.normalizrSchema
	}))
}
Ejemplo n.º 6
0
export function *handleSelectedBoardsDeleteRequest(): Generator<any, *, *> {
  while (true) {
    yield take(B.SELECTED_BOARDS_DELETE_REQUEST);
    const entities: ?BoardEntities = yield select(getSelectedBoardEntities);

    try {
      if (!entities) throw new Error("ボードが選択されていません");

      const response = yield call((): Promise<{ boards: Boards }> => Services.deleteBoards(entities));
      if (!response) throw new Error("選択したボードの削除に失敗しました");

      const normalized = normalize(response, { boards: arrayOf(BoardSchema) });
      yield put(B.selectedBoardsDeleteSuccess(normalized));

    } catch (error) {
      yield put(B.selectedBoardsDeleteFailure(error, entities));
    }
  }
}
Ejemplo n.º 7
0
// import * as Schema from '../../schema';

/**
 * @event INITIALIZE_GAME
 * @param {__PROTO.ApiRequest} r
 */
export default function (r:ApiRequest):ApiRequestResult {
  const {
          api_mst_ship,
          api_mst_shipgraph,
          api_mst_shipupgrade,
          api_mst_slotitem,
          api_msg_slotitem_equiptype,
          api_mst_equip_exslot,
          api_mst_stype,
          api_mst_furniture,
          api_mst_furnituregraph,
          api_mst_useitem,
          api_mst_payitem,
          api_mst_item_shop,
          api_mst_maparea,
          api_mst_mapinfo,
          api_mst_mapbgm,
          api_mst_mapcell,
          api_mst_mission,
          api_mst_const,
          api_mst_bgm,
        } = r.body;

  const response = {
    ships: R.map(baseShip, r.body.api_mst_ship)
  };

  const baseShip_Schema = new Schema('ships', { idAttribute: 'shipId' });

  const result = normalize(response, {
    ships: baseShip_Schema
  });

  console.log('normalized =>', result);

  return {
    normalized: result,
    ships: api_mst_ship.map(baseShip),
    shipGraphics: api_mst_shipgraph.map(baseShipGraphic),
    shipTypes: api_mst_stype.map(baseShipType),
    slotItems: api_mst_slotitem.map(baseSlotItem)
  };
}
Ejemplo n.º 8
0
            .then(json => {
                /*
                Set pagination URLs nextUrl and futureUrl.
                */
                let nextUrl = null;
                let futureUrl = null;
                if (json.next_href) {
                    nextUrl = json.next_href;
                    nextUrl += (authed.accessToken ? `oauth_token=${authed.accessToken}` : "");
                }

                if (json.future_href) {
                    futureUrl = json.future_href;
                    futureUrl += (authed.accessToken ? `oauth_token=${authed.accessToken}` : "");
                }

                /*
                Preprocess the songs in the playlist and normalize the results.
                */
                const songs = json.collection
                    .map(song => song.origin || song)
                    .filter(song => {
                        return song.streamable && song.kind == "track"; //we only want streamable songs!
                    });

                const normalized = normalize(songs, arrayOf(songSchema));
                const songIds = normalized.result.reduce((arr, songId) => {
                    if (arr.indexOf(songId) === -1) {
                        arr.push(songId); //no duplicate songs in our playlist - only unique ones.
                    }

                    return arr;
                }, []);

                dispatch(receiveSongs({
                    songs: normalized.entities.songs,
                    users: normalized.entities.users,
                    songIds: songIds,
                    playlistId: playlistId,
                    nextUrl: nextUrl,
                    futureUrl: futureUrl
                }));
            })
Ejemplo n.º 9
0
export function *handleDeleteTagRequest(): Generator<any, *, *> {
  while (true) {
    const action: ?DeleteTagRequestAction = yield take(T.DELETE_TAG_REQUEST);

    try {
      if (!action) throw new Error("タグの削除に失敗しました");

      const response = yield call((): Promise<{ tag: Tag }> => Services.deleteTag(action.payload));
      if (!response) throw new Error("タグの削除に失敗しました");

      const normalized = normalize(response, {
        tag: TagSchema
      });
      yield put(T.deleteTagSuccess(normalized));

    } catch (error) {
      yield put(T.deleteTagFailure(error, action ? action.payload : null));
    }
  }
}
Ejemplo n.º 10
0
export function* loadFeed({ host = 'github', participating }) {
  try {
    const token = yield select(getToken, host);
    let feed = yield call(api.fetchFeed, host, token, { participating });
    feed = normalize(feed, arrayOf(post), { assignEntity });
    const result = feed.result;
    const count = result.length;
    updateTrayIcon(count);
    const posts = yield select(getPosts, host);
    const firstDiff = !posts || result[0] !== posts.first();
    if (posts && firstDiff) notify(feed);

    if (firstDiff || result[count - 1] !== posts.last()) {
      yield put(fetchFeed.success({ host, payload: groupByTarget(feed) }));
    } else yield put(fetchFeed.success());
  } catch (error) {
    console.error(error);
    yield put(fetchFeed.error(error));
  }
}
Ejemplo n.º 11
0
    return async function(dispatch, getState) {
        const isPublicLink = Utils.isUUID(dashId);
        if (isPublicLink) {
            result = await PublicApi.dashboard({ uuid: dashId });
            result = {
                ...result,
                id: dashId,
                ordered_cards: result.ordered_cards.map(dc => ({
                    ...dc,
                    dashboard_id: dashId
                }))
            };
        } else {
            result = await DashboardApi.get({ dashId: dashId });
        }

        dispatch(setDashboardId(dashId));

        if (result.parameters) {
            for (const parameter of result.parameters) {
                if (queryParams && queryParams[parameter.slug] != null) {
                    dispatch(setParameterValue(parameter.id, queryParams[parameter.slug]));
                } else if (enableDefaultParameters && parameter.default != null) {
                    dispatch(setParameterValue(parameter.id, parameter.default));
                }
            }
        }

        if (!isPublicLink) {
            // fetch database metadata for every card
            _.chain(result.ordered_cards)
                .map((dc) => [dc.card].concat(dc.series))
                .flatten()
                .filter(card => card && card.dataset_query && card.dataset_query.database)
                .map(card => card.dataset_query.database)
                .uniq()
                .each((dbId) => dispatch(fetchDatabaseMetadata(dbId)));
        }

        return normalize(result, dashboard);
    };
Ejemplo n.º 12
0
export const fetchRepos = username => async dispatch => {
  await dispatch({
    type: FETCH_REPOS,
    payload: { username },
  });

  try {
    const response = await fetch(`${API_HOST}/users/${username}/repos`);
    const json = await response.json();

    return dispatch({
      type: FETCH_REPOS_SUCCESS,
      payload: normalize(json, repos),
    });
  } catch (error) {
    return dispatch({
      type: FETCH_REPOS_FAILURE,
      payload: error,
    });
  }
};
Ejemplo n.º 13
0
export const fetchNewStreamSongs = url => async (dispatch, getState) => {
  const { json } = await callApi(url);
  const { playlists } = getState();
  const items = SESSION_STREAM_PLAYLIST in playlists
    ? playlists[SESSION_STREAM_PLAYLIST].items
    : [];
  const itemsMap = items.reduce((obj, id) => ({ ...obj, [id]: 1 }), {});

  const { collection, futureHref } = json;

  const futureUrl = futureHref || null;
  const songs = collection
    .filter(song =>
      song.kind === 'track'
      && song.streamable
      && !(song.id in itemsMap));

  const { result, entities } = normalize(songs, [songSchema]);

  dispatch(fetchNewStreamSongsSuccess([...new Set(result)], entities, futureUrl));
};
Ejemplo n.º 14
0
export function *handleSelectedItemsMoveRequest(action: SelectedItemsMoveRequestAction): Generator<any, *, *> {
  let entities: ?ItemEntities = null;
  let prevBoards: Array<BoardId> = [];

  try {
    entities = yield select(getSelectedItemEntities);
    if (!entities || entities.length === 0) throw new Error("アイテムが選択されていません");

    prevBoards = entities.map(entity => entity.board_id);

    const newEntities = entities.map(entity => ({ ...entity, board_id: action.payload }));
    const response = yield call(Services.updateItems, newEntities);
    if (!response) throw new Error("選択したアイテムの移動に失敗しました");

    const normalized = normalize(response, { items: arrayOf(ItemSchema) });
    yield put(I.selectedItemsMoveSuccess(normalized, prevBoards));

  } catch (error) {
    yield put(I.selectedItemsMoveFailure(error, entities, prevBoards, action.payload));
  }
}
Ejemplo n.º 15
0
    return async function(dispatch, getState) {
        let result = await DashboardApi.get({ dashId: id });
        if (result.parameters) {
            const { query } = getState().router.location;
            for (const parameter of result.parameters) {
                if (enableQueryParameters && query[parameter.slug] != null) {
                    dispatch(setParameterValue(parameter.id, query[parameter.slug]));
                } else if (enableDefaultParameters && parameter.default != null) {
                    dispatch(setParameterValue(parameter.id, parameter.default));
                }
            }
        }
        _.chain(result.ordered_cards)
            .map((dc) => [dc.card].concat(dc.series))
            .flatten()
            .map(card => card.dataset_query && card.dataset_query.database)
            .uniq()
            .each((dbId) => dispatch(fetchDatabaseMetadata(dbId)));

        return normalize(result, dashboard);
    };
Ejemplo n.º 16
0
export function *handleSelectedItemsDeleteRequest(): Generator<any, *, *> {
  while (true) {
    yield take(I.SELECTED_ITEMS_DELETE_REQUEST);
    let entities: ?ItemEntities = null;

    try {
      entities = yield select(getSelectedItemEntities);
      if (!entities) throw new Error("アイテムの削除に失敗しました");

      const validEntities: ItemEntities = entities;
      const response = yield call((): Promise<{ items: Items }> => Services.deleteItems(validEntities));
      if (!response) throw new Error("選択したアイテムの削除に失敗しました");

      const normalized = normalize(response, { items: arrayOf(ItemSchema) });
      yield put(I.selectedItemsDeleteSuccess(normalized));

    } catch (error) {
      yield put(I.selectedItemsDeleteFailure(error, entities));
    }
  }
}
Ejemplo n.º 17
0
  (dispatch, getState) => {
    if (getIsFormSaving(getState(), dateId)) {
      return Promise.resolve();
    }

    const date = getDate(getState(), dateId);
    date.riskAssessmentFormPending = true;
    date.riskAssessmentMeta = data ?
      JSON.stringify(data) :
      '';

    dispatch({
      type: 'FORM_SAVE_ANSWERS_REQUEST',
      dateId,
      data,
      response: normalize(date, schema.date),
    });

    const promise = api.dates.saveForm(dateId, data, !!confirmAssessment);
    promise.then(
      (response) => {
        dispatch({
          type: 'FORM_SAVE_ANSWERS_SUCCESS',
          dateId,
          response: normalize(response, schema.date),
        });
      },
      (error) => {
        dispatch({
          type: 'FORM_SAVE_ANSWERS_FAILURE',
          dateId,
          message: error.message || 'Noe gikk galt',
        });
      }
    );

    return promise;
  };
Ejemplo n.º 18
0
    (response) => {
      dispatch({
        type: 'FETCH_LIST_SUCCESS',
        data: normalize(response.results, arrayOfAnnouncements),
      });
      dispatch({
        type: 'SET_LIST_NEXT_URL',
        next: response.next,
        prev: response.previous,
      });

      // Mark as seen
      if (seenTimerHandler) {
        clearTimeout(seenTimerHandler);
      }
      seenTimerHandler = setTimeout(() => {
        getAnnouncements(getState())
          .filter((announcement) => !announcement.seen)
          .forEach((announcement) => {
            seen(announcement.id)(dispatch, getState);
          });
      }, 3000);
    },
Ejemplo n.º 19
0
Archivo: api.js Proyecto: 1ven/do
    .then(({ response, body }) => {
      if (!response.ok) {
        return Promise.reject(body);
      }

      const camelized = camelcaseKeysDeep(body.result || {});
      const receivedAt = Date.now();
      const { notification } = body;

      if (schema) {
        return {
          ...normalize(camelized, schema),
          notification,
          receivedAt,
        };
      }

      return {
        result: camelized,
        notification,
        receivedAt,
      };
    });
Ejemplo n.º 20
0
export function *handleDeleteBoardRequest(): Generator<any, *, *> {
  while (true) {
    let entity: ?BoardEntity = null;

    try {
      const action: ?DeleteBoardRequestAction = yield take(B.DELETE_BOARD_REQUEST);
      if (!action) throw new Error("ボードの削除に失敗しました");

      entity = yield select(getBoardEntityById, action.payload);
      if (!entity) throw new Error("ボードの削除に失敗しました");

      const validEntity: BoardEntity = entity;
      const response = yield call((): Promise<{ boards: Boards }> => Services.deleteBoards([validEntity]));
      if (!response) throw new Error(`${validEntity.name} の削除に失敗しました`);

      const normalized = normalize({ board: response.boards[0] }, { board: BoardSchema });
      yield put(B.deleteBoardSuccess(normalized));

    } catch (error) {
      yield put(B.deleteBoardFailure(error, entity));
    }
  }
}
Ejemplo n.º 21
0
          getData: async () => {
            const fetched = await entity.api.list(entityQuery || {});
            let results = fetched;

            // for now at least paginated endpoints have a 'data' property that
            // contains the actual entries, if that is on the response we should
            // use that as the 'results'
            if (fetched.data) {
              results = fetched.data;
            }
            const { result, entities } = normalize(results, [entity.schema]);
            return {
              result,
              entities,
              entityQuery,
              // capture some extra details from the result just in case?
              resultDetails: {
                total: fetched.total,
                offset: fetched.offset,
                limit: fetched.limit,
              },
            };
          },
Ejemplo n.º 22
0
export function *handleDeleteItemRequest(): Generator<any, *, *> {
  while (true) {
    let entity: ?ItemEntity = null;

    try {
      const action: ?DeleteItemRequestAction = yield take(I.DELETE_ITEM_REQUEST);
      if (!action) throw new Error("アイテムの削除に失敗しました");

      entity = yield select(getItemEntityById, action.payload);
      if (!entity) throw new Error("指定したアイテムが存在しません");

      const validEntity: ItemEntity = entity;
      const response = yield call((): Promise<{ items: Items }> => Services.deleteItems([validEntity]));
      if (!response) throw new Error(`${entity.name} の削除に失敗しました`);

      const normalized = normalize({ item: response.items[0] }, { item: ItemSchema });
      yield put(I.deleteItemSuccess(normalized));

    } catch (error) {
      yield put(I.deleteItemFailure(error, entity));
    }
  }
}
Ejemplo n.º 23
0
	it('should normalize payload if action.meta.schema is set', () => {

		const payload = [ {id: 1}, {id: 2} ];
		const schema = arrayOf(new Schema('test_obj'));

		const action = {
			type: 'TEST',
			meta: { schema },
			payload,
		};

		const expectedActions = [
			{
				...action,
				payload: normalize(payload, schema),
			},
		];

		const store = mockStore({});
		store.dispatch(action);
		const actions = store.getActions();

		assert.deepEqual(actions, expectedActions);
	})
Ejemplo n.º 24
0
export function* addCorePackagesSaga() {
  yield put(actions.corePackagesRequested());
  try {
    // Call the API.
    const env = isDev ? 'dev' : 'prod';
    const isPre = window.location.host.startsWith('pre') ||
      window.location.host.startsWith('localhost');
    const cdn = isPre ? 'precdn' : 'cdn';
    const res = isRemote
      ? yield call(request.get, `https://${cdn}.worona.io/api/v1/settings/core/dashboard/${env}`)
      : defaultPackages;
    // Normalize the result using normalizr.
    const pkgs = {
      ...normalize(res.body, schemas.arrayOfPackages).entities.packages,
      ...getDevelopmentPackages(),
    };
    // Inform that the API call was successful.
    yield put(actions.corePackagesSucceed({ pkgs }));
    // Start activation for each downloaded package.
    yield toArray(pkgs).map(pkg => put(actions.packageActivationRequested({ pkg })));
  } catch (error) {
    yield put(actions.corePackagesFailed({ error: error.message }));
  }
}
Ejemplo n.º 25
0
const TournamentReducer = (state = initState, action) => {
    switch(action.type) {

        case REQUEST_TOURNAMENTS:
            return { ...state, isFetching: true  }

        case RECEIVE_TOURNAMENTS:
            return { ...state,
                isFetching: false,
                tournaments: action.tournaments,
                normTour:    normalize(action.tournaments, arrayOf(TournamentSchema))
            }
        case "SET_ACTIVE_TOURNAMENT":
            return { ...state,
                activeTournament: state.normTour.entities.tournaments[action.tournamentId]
            }
        case "SCORE_UPDATED":
            return {
                ...state
            }
    }

    return state
}
Ejemplo n.º 26
0
export function *handleMoveItemRequest(action: MoveItemRequestAction): Generator<any, *, *> {
  let entity: ?ItemEntity = null;
  let prevBoard: ?BoardId = null;

  try {
    const entities: ?ItemEntities = yield select(getMoveItemEntities);
    if (!entities || entities.length === 0) throw new Error("移動するアイテムが存在しません");

    entity = entities[0];
    const validEntity: ItemEntity = entity;
    prevBoard = validEntity.board_id;
    const prev = validEntity.board_id;
    const newEntity: ItemEntity = { ...validEntity, board_id: action.payload };

    const response = yield call((): Promise<{ items: Items }> => Services.updateItems([newEntity]));
    if (!response) throw new Error(`${validEntity.name} の移動に失敗しました`);

    const normalized = normalize({ item: response.items[0] }, { item: ItemSchema });
    yield put(I.moveItemSuccess(normalized, prev));

  } catch (error) {
    yield put(I.moveItemFailure(error, entity, prevBoard, action.payload));
  }
}
Ejemplo n.º 27
0
  describe("parsing interdependents objects", () => {
    const articleSchema = new Schema('articles');
    const userSchema = new Schema('users');

    articleSchema.define({
      author: userSchema,
    });

    userSchema.define({
      articles: arrayOf(articleSchema),
    });

    const response = {
      articles: [{
        id: 80,
        title: 'Some Article',
        author: {
          id: 1,
          name: 'Dan',
          articles: [80],
        }
      }]
    };

    const data = normalize(response, {
      articles: arrayOf(articleSchema)
    });

    it("should handle recursion for interdependency", () => {
      const article = data.entities.articles["80"];
      const denormalized = denormalize(article, data.entities, articleSchema);

      expect(denormalized.author.articles[0]).to.be.eql(denormalized);
    });

  });
 .then(response => normalize(response || {}, categoriesSchema));
Ejemplo n.º 29
0
 .then((response) => (schema ? normalize(response, schema) : response));
 .then(response => normalize(response || {}, valuesOf(categoriesSchema)));