Get NPM Component from Name & version - Sonatype Nexus Repository - Sonatype Community

Get NPM Component from Name & version

post by manojpdn on Mar 7, 2021

I need to get the NPM component by using the name and the version. What is the method that I can use here? For maven, I’ve used the below method.

    HashMap<String, String> filter = new HashMap<>(1);
    filter.put("version", coords.getVersion());
     componentStore.getAllMatchingComponents(
            context.getRepository(), coords.getGroupId(), coords.getArtifactId(), filter)

post by manojpdn on Mar 10, 2021

@mpiggott @dsawa Do you have any idea about this? I need to get Component or Asset object using the repository, name & version.

Ex: “logback”: “1.0.16”

post by jmcpherson on Mar 11, 2021

The typical format for npm is:

npm install logback@1.0.16 --save

, or for a dev dependency

npm install logback@1.0.16 --save-dev

post by manojpdn on Mar 12, 2021

I need to get component or asset by using repository, artifact name and version. Below method is for Maven. Is there any method for NPM as npm doesn’t have group Id.

        componentStore.getAllMatchingComponents(
        context.getRepository(), coords.getGroupId(), coords.getArtifactId(), filter)

post by manojpdn on Mar 22, 2021

We can write a custom query method to get components by name & version.

    private List<Component> getAllMatchingComponents(Repository repository, String name, Map<String, String> formatAttributes) {
    Preconditions.checkNotNull(repository);
    Preconditions.checkNotNull(name);
    Preconditions.checkNotNull(formatAttributes);
    List<Component> filteredComponents;
    try (StorageTx storageTx = repository.facet(StorageFacet.class).txSupplier().get()) {
        storageTx.begin();
        Query.Builder query = Query.builder().where("name").eq(name).suffix("order by version desc");
        Iterable<Component> unfilteredComponents = storageTx.findComponents(query.build(), Collections.singletonList(repository));
        Stream<Component> filteredStream = StreamSupport.stream(unfilteredComponents.spliterator(), false).filter(
                component -> formatAttributes.entrySet().stream().allMatch(
                        entry -> Objects.equals(entry.getValue(), component.version())));
        filteredComponents = ImmutableList.copyOf(filteredStream.iterator());
    }

return filteredComponents;
}