lodash-es#orderBy TypeScript Examples

The following examples show how to use lodash-es#orderBy. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: fetchHooks.ts    From github-deploy-center with MIT License 6 votes vote down vote up
useFetchWorkflows = () => {
  const { token, selectedApplication } = useAppState()
  const { restApi } = useEffects()

  const repo = selectedApplication?.repo

  const { data, isLoading, error } = useQuery(
    `${repo?.owner}/${repo?.name}/workflows`,
    async () => {
      if (!token || !repo) return []

      const { owner, name } = repo

      const response = await restApi.octokit.actions.listRepoWorkflows({
        owner,
        repo: name,
        per_page: 100,
      })

      // TODO: Only return workflows with `workflow_dispatch` trigger
      return orderBy(response.data?.workflows ?? [], (w) => w.name)
    }
  )
  return { data, isLoading, error }
}
Example #2
Source File: SelectApplicationView.tsx    From github-deploy-center with MIT License 6 votes vote down vote up
SelectApplicationView = () => {
  const { applicationsById, selectedApplicationId } = useAppState()
  const { selectApplication, editApplication, editDeployment } = useActions()
  const sortedApplications = orderBy(applicationsById, (x) =>
    x.name.toLowerCase()
  )
  return size(sortedApplications) ? (
    <Box display="flex" alignItems="center" style={{ gap: '1rem' }}>
      <FormControl variant="outlined" style={{ flex: 1 }}>
        <InputLabel id="application-select-label">Application</InputLabel>
        <Select
          labelId="application-select-label"
          label="Application"
          onChange={(event) => {
            selectApplication(event.target.value as string)
          }}
          value={selectedApplicationId}>
          {map(sortedApplications, (app) => (
            <MenuItem value={app.id} key={app.id}>
              {app.name}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
      <Button color="secondary" variant="contained" onClick={editApplication}>
        Edit App
      </Button>
      <Button color="secondary" variant="contained" onClick={editDeployment}>
        Edit Deploy
      </Button>
    </Box>
  ) : null
}
Example #3
Source File: fetchHooks.ts    From github-deploy-center with MIT License 5 votes vote down vote up
useFetchReleases = () => {
  const { selectedApplication, appSettings } = useAppState()

  const repo = selectedApplication?.repo
  const prefix = selectedApplication?.releaseFilter ?? ''

  const { data, isLoading, error } = useQuery(
    `${repo?.owner}/${repo?.name}/releases/${prefix}`,
    async () => {
      if (!repo) return []

      const result = await graphQLApi.fetchReleases({
        repoName: repo.name,
        repoOwner: repo.owner,
        prefix,
      })
      const fragments = result.repository?.refs?.nodes?.map((n) => n!) ?? []
      const releases = fragments
        .map(({ id, name, target }): ReleaseModel | null =>
          target?.__typename === 'Commit'
            ? {
                id,
                name,
                tagName: name,
                createdAt: dayjs(target.pushedDate ?? target.committedDate),
                commit: target.oid,
                deployments:
                  target.deployments?.nodes
                    ?.filter((node) => !!node)
                    .map((n) => n! as DeployFragment)
                    .map(
                      ({
                        id,
                        createdAt,
                        environment,
                        state,
                        latestStatus,
                      }): DeploymentModel => ({
                        id,
                        createdAt: dayjs(createdAt),
                        environment: environment || '',
                        state: state || DeploymentState.Inactive,
                        modifiedAt: dayjs(latestStatus?.createdAt),
                      })
                    )
                    .orderBy((n) => n.createdAt, 'desc') || [],
              }
            : null
        )
        .filter((n): n is ReleaseModel => !!n)
      return releases
    },
    {
      refetchInterval: 1000 * appSettings.refreshIntervalSecs,
    }
  )

  return { data, isLoading, error }
}
Example #4
Source File: extensions.ts    From github-deploy-center with MIT License 5 votes vote down vote up
// eslint-disable-next-line no-extend-native
Array.prototype['orderBy'] = function <T>(
  this: Array<T>,
  selector: (t: T) => any,
  order?: 'asc' | 'desc'
): Array<T> {
  return orderBy(this, selector, order)
}
Example #5
Source File: ApplicationDialog.tsx    From github-deploy-center with MIT License 4 votes vote down vote up
ApplicationDialog: FC<{
  dialogState?: ApplicationDialogState
  newOrEdit: 'new' | 'edit'
  title: string
  onSave: ({
    repo,
    name,
    releaseFilter,
  }: {
    repo: RepoModel
    name: string
    releaseFilter: string
  }) => void
  onCancel: () => void
}> = ({ dialogState, newOrEdit, title, onSave, onCancel }) => {
  const { data, error, isLoading } = useFetchRepos()
  const { updateApplicationDialog, deleteApplication } = useActions()
  const updateDialogState = (update: (state: ApplicationDialogState) => void) =>
    updateApplicationDialog({ newOrEdit, update })
  const options = orderBy(data ?? [], (d) => d.owner.toLowerCase())
  return (
    <Dialog open={!!dialogState} fullWidth onClose={onCancel}>
      {dialogState ? (
        <form
          onSubmit={(event) => {
            event.preventDefault()
            dialogState.repo &&
              onSave({
                repo: dialogState.repo,
                name: dialogState.name,
                releaseFilter: dialogState.releaseFilter,
              })
          }}>
          <DialogTitle>{title}</DialogTitle>
          <DialogContent>
            {error instanceof Error ? (
              <Alert severity="error">{error.message}</Alert>
            ) : (
              <>
                <DialogContentText>Select repository</DialogContentText>
                <Box
                  display="flex"
                  flexDirection="column"
                  style={{ gap: '1rem' }}>
                  <RepoSearchBox
                    isLoading={isLoading}
                    options={options}
                    selectedRepo={dialogState.repo}
                    setSelectedRepo={(repo) =>
                      updateDialogState((state) => (state.repo = repo))
                    }
                  />
                  <TextField
                    variant="outlined"
                    label="Name"
                    inputProps={{
                      'data-lpignore': true,
                    }}
                    placeholder="Defaults to same as repository"
                    value={dialogState.name}
                    fullWidth
                    onChange={(event) => {
                      updateDialogState(
                        (state) => (state.name = event.target.value)
                      )
                    }}
                  />
                  <Box
                    display="flex"
                    alignItems="center"
                    style={{ gap: '1rem' }}>
                    <TextField
                      style={{ flex: 2 }}
                      variant="outlined"
                      label="Release filter prefix"
                      placeholder="Filter which release tags to show for this application"
                      value={dialogState.releaseFilter}
                      fullWidth
                      onChange={(event) =>
                        updateDialogState(
                          (state) =>
                            (state.releaseFilter =
                              event.target.value.toLowerCase())
                        )
                      }
                    />
                    <Button
                      color="secondary"
                      variant="contained"
                      onClick={() =>
                        updateDialogState(
                          (state) =>
                            (state.releaseFilter =
                              state.name.toLowerCase().replaceAll(' ', '-') +
                              '-v')
                        )
                      }>
                      Set filter from name
                    </Button>
                  </Box>
                </Box>

                {dialogState.warning && (
                  <Box mt={2}>
                    <Alert severity="warning">{dialogState.warning}</Alert>
                  </Box>
                )}
              </>
            )}
          </DialogContent>
          <Box p={2} pt={1}>
            <DialogActions>
              {newOrEdit === 'edit' && (
                <Button
                  style={{ color: theme.palette.error.main }}
                  onClick={deleteApplication}>
                  Delete
                </Button>
              )}
              <Expander />
              <Button
                type="submit"
                disabled={!dialogState.repo || !!dialogState.warning}
                variant="contained"
                color="primary">
                Save
              </Button>
              <Button onClick={onCancel}>Cancel</Button>
            </DialogActions>
          </Box>
        </form>
      ) : null}
    </Dialog>
  )
}
Example #6
Source File: ReleasesTableView.tsx    From github-deploy-center with MIT License 4 votes vote down vote up
ReleasesTableView = () => {
  const { selectedApplication, pendingDeployments } = useAppState()
  const repo = selectedApplication?.repo
  const { triggerDeployment, removeEnvironment } = useActions()
  const allReleaseResultsForTag = useFetchReleases()

  const releases = allReleaseResultsForTag.data || []

  const { mutate, error, isLoading } = useMutation(
    async ({
      release,
      environmentName,
    }: {
      release: string
      environmentName: string
    }) => {
      await triggerDeployment({ release, environmentName })
    }
  )

  if (
    !selectedApplication ||
    !DeployWorkflowCodec.is(selectedApplication.deploySettings) ||
    !selectedApplication.deploySettings.workflowId
  ) {
    return null
  }

  if (allReleaseResultsForTag.isLoading) {
    return <CircularProgress />
  }

  const releasesSorted = orderBy(
    releases
      .slice()
      .sort((a, b) =>
        b.tagName.localeCompare(a.tagName, undefined, { numeric: true })
      )
      .filter((r) =>
        r.name
          .toLowerCase()
          .startsWith(selectedApplication.releaseFilter.toLowerCase())
      ),
    (r) => r.createdAt,
    'desc'
  )

  const selectedEnvironments = values(
    selectedApplication.environmentSettingsByName
  )

  const releasesByEnvironment = selectedEnvironments.reduce<
    Record<string, ReleaseModel[]>
  >((record, environment) => {
    record[environment.name] = releasesSorted.filter((r) =>
      r.deployments.some((d) => d.environment === environment.name)
    )
    return record
  }, {})

  const createButton = (
    deployment: DeploymentModel | undefined,
    release: ReleaseModel,
    environment: EnvironmentSettings
  ) => {
    const latestRelease = releasesByEnvironment[environment.name]?.[0]
    const isAfterLatest =
      !latestRelease || release.createdAt.isAfter(latestRelease.createdAt)

    const deploymentId = getDeploymentId({
      release: release.tagName,
      environment: environment.name,
      repo: selectedApplication.repo.name,
      owner: selectedApplication.repo.owner,
    })
    const pendingDeployment = pendingDeployments[deploymentId]
    const modifiedAt = deployment?.modifiedAt
    const deploymentState =
      pendingDeployment &&
      (!modifiedAt || pendingDeployment.isAfter(modifiedAt))
        ? DeploymentState.Pending
        : deployment?.state

    const deployButtonVariant =
      (isAfterLatest && !deploymentState) ||
      deploymentState === DeploymentState.Active
        ? 'contained'
        : 'outlined'

    return (
      <Button
        disabled={isLoading}
        variant={deployButtonVariant}
        color={!deploymentState && isAfterLatest ? 'primary' : 'default'}
        style={getButtonStyle(deploymentState)}
        onClick={() =>
          mutate({
            release: release.tagName,
            environmentName: environment.name,
          })
        }>
        {deploymentState?.replaceAll('_', ' ') ?? 'Deploy'}
      </Button>
    )
  }

  return (
    <>
      {error instanceof Error && (
        <Alert severity="error">{error.message}</Alert>
      )}
      <Table>
        <TableHead>
          <TableRow>
            <TableCell>Release name</TableCell>
            {selectedEnvironments.map((environment) => (
              <TableCell key={environment.name}>
                <Link
                  href={`https://github.com/${repo?.owner}/${
                    repo?.name
                  }/deployments/activity_log?environment=${encodeURIComponent(
                    environment.name
                  )}`}
                  target="_blank"
                  color="inherit">
                  {environment.name}
                </Link>
                <IconButton onClick={() => removeEnvironment(environment.name)}>
                  <Icon>delete</Icon>
                </IconButton>
              </TableCell>
            ))}
          </TableRow>
        </TableHead>
        <TableBody>
          {releasesSorted.map((release) => (
            <TableRow key={release.id}>
              <TableCell style={{ width: '20%' }}>
                <Link
                  href={`https://github.com/${repo?.owner}/${repo?.name}/releases/tag/${release.tagName}`}
                  target="_blank"
                  color="inherit">
                  {release.name}
                </Link>
              </TableCell>
              {selectedEnvironments.map((environment) => {
                const deployment = release.deployments.find(
                  (d) => d.environment === environment.name
                )
                return (
                  <TableCell key={environment.name}>
                    {createButton(deployment, release, environment)}
                  </TableCell>
                )
              })}
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </>
  )
}