Skip to content

feat(user page): Recently published #955

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

28 changes: 28 additions & 0 deletions api/src/api.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1299,6 +1299,34 @@ paths:
schema:
$ref: "#/components/schemas/Error"

/users/{id}/packages:
get:
summary: List recently published packages by user
description: Returns a list of packages that a user has recently published
operationId: listUserPackages
parameters:
- name: id
in: path
description: The ID of the user
required: true
schema:
$ref: "#/components/schemas/UserId"
responses:
"200":
description: OK
content:
application/json:
schema:
type: array
items:
$ref: "#/components/schemas/Package"
"404":
description: User not found
content:
application/json:
schema:
$ref: "#/components/schemas/Error"

/authorizations:
post:
summary: Create authorization
Expand Down
24 changes: 24 additions & 0 deletions api/src/api/users.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@ use crate::util::ApiResult;
use crate::util::RequestIdExt;

use super::ApiError;
use super::ApiPackage;
use super::ApiScope;
use super::ApiUser;

pub fn users_router() -> Router<Body, ApiError> {
Router::builder()
.get("/:id", util::json(get_handler))
.get("/:id/scopes", util::json(get_scopes_handler))
.get("/:id/packages", util::json(get_packages_handler))
.build()
.unwrap()
}
Expand Down Expand Up @@ -54,3 +56,25 @@ pub async fn get_scopes_handler(

Ok(scopes.into_iter().map(ApiScope::from).collect())
}

#[instrument(name = "GET /api/users/:id/packages", skip(req), err, fields(id))]
pub async fn get_packages_handler(
req: Request<Body>,
) -> ApiResult<Vec<ApiPackage>> {
let id = req.param_uuid("id")?;
Span::current().record("id", field::display(id));

let db = req.data::<Database>().unwrap();
db.get_user_public(id)
.await?
.ok_or(ApiError::UserNotFound)?;

let packages = db.get_recent_packages_by_user(&id).await?;

Ok(
packages
.into_iter()
.map(|package| ApiPackage::from((package, None, Default::default())))
.collect(),
)
}
49 changes: 49 additions & 0 deletions api/src/db/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4840,6 +4840,55 @@ impl Database {

Ok((total_scopes as usize, scopes))
}

pub async fn get_recent_packages_by_user(
&self,
user_id: &uuid::Uuid,
) -> Result<Vec<Package>> {
let packages = sqlx::query_as!(
Package,
r#"
SELECT DISTINCT ON (packages.scope, packages.name)
packages.scope as "scope: ScopeName",
packages.name as "name: PackageName",
packages.description,
packages.github_repository_id,
packages.runtime_compat as "runtime_compat: RuntimeCompat",
packages.when_featured,
packages.is_archived,
packages.readme_source as "readme_source: ReadmeSource",
packages.updated_at,
packages.created_at,
(
SELECT COUNT(created_at)
FROM package_versions
WHERE scope = packages.scope AND name = packages.name
) as "version_count!",
(
SELECT version
FROM package_versions
WHERE scope = packages.scope
AND name = packages.name
AND version NOT LIKE '%-%'
AND is_yanked = false
ORDER BY version DESC LIMIT 1
) as "latest_version"
FROM publishing_tasks
JOIN packages
ON packages.scope = publishing_tasks.package_scope
AND packages.name = publishing_tasks.package_name
WHERE publishing_tasks.user_id = $1
AND publishing_tasks.status = 'success'
ORDER BY packages.scope, packages.name, publishing_tasks.created_at DESC
LIMIT 10;
"#,
user_id
)
.fetch_all(&self.pool)
.await?;

Ok(packages)
}
}

async fn finalize_package_creation(
Expand Down
36 changes: 26 additions & 10 deletions frontend/routes/user/[id].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { HttpError } from "fresh";
import { define } from "../../util.ts";
import { path } from "../../utils/api.ts";
import { FullUser, Scope, User } from "../../utils/api_types.ts";
import { FullUser, Package, Scope, User } from "../../utils/api_types.ts";
import { ListPanel } from "../../components/ListPanel.tsx";
import { AccountLayout } from "../account/(_components)/AccountLayout.tsx";

Expand Down Expand Up @@ -32,25 +32,39 @@ export default define.page<typeof handler>(function UserPage({ data, state }) {
</div>
)}

{
/*<div>
<span class="font-semibold">Recently published</span>
<div class="text-tertiary text-base"
TODO: all packages recently published by this user
</div>
</div>*/
}
{data.packages.length > 0
? (
<ListPanel
title="Recently published"
subtitle={state.user?.id === data.user.id
? "Packages you have published."
: "Packages this user has published."}
// deno-lint-ignore jsx-no-children-prop
children={data.packages.map((pkg) => ({
value: `@${pkg.scope}/${pkg.name}`,
href: `/@${pkg.scope}/${pkg.name}`,
}))}
/>
)
: (
<div class="p-3 text-jsr-gray-500 text-center italic">
{state.user?.id === data.user.id ? "You have" : "This user has"}
{" "}
not published any packages recently.
</div>
)}
</div>
</AccountLayout>
);
});

export const handler = define.handlers({
async GET(ctx) {
const [currentUser, userRes, scopesRes] = await Promise.all([
const [currentUser, userRes, scopesRes, packagesRes] = await Promise.all([
ctx.state.userPromise,
ctx.state.api.get<User>(path`/users/${ctx.params.id}`),
ctx.state.api.get<Scope[]>(path`/users/${ctx.params.id}/scopes`),
ctx.state.api.get<Package[]>(path`/users/${ctx.params.id}/packages`),
]);
if (currentUser instanceof Response) return currentUser;

Expand All @@ -62,6 +76,7 @@ export const handler = define.handlers({
throw userRes; // gracefully handle errors
}
if (!scopesRes.ok) throw scopesRes; // gracefully handle errors
if (!packagesRes.ok) throw packagesRes; // gracefully handle errors

let user: User | FullUser = userRes.data;
if (ctx.params.id === currentUser?.id) {
Expand All @@ -75,6 +90,7 @@ export const handler = define.handlers({
data: {
user,
scopes: scopesRes.data,
packages: packagesRes.data,
},
};
},
Expand Down