npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

mad-spring-enum

v1.0.0

Published

Sharing enums with a Java Spring Boot back-end.

Downloads

65

Readme

About

Build Status Codecov

Sharing enums with a Java Spring Boot back-end.

Installation

npm install mad-spring-enum --save

Preparation

First in your Java project make sure mad-spring-enum can read the enums, via a GET request:

// EnumController.java

@RestController
@RequestMapping("/enums")
class EnumController {

    private final Map<String, Set<String>> registry = new HashMap<>();

    @Autowired
    EnumController(EnumClassPathScanningCandidateComponentProvider enumProvider) {
        enumProvider.findCandidateComponents(Application.class.getPackage().getName())
            .forEach(component -> {
                Class<Enum<?>> componentClass = forName(component.getBeanClassName());
                registry.put(componentClass.getSimpleName(), stream(componentClass.getEnumConstants())
                    .map(Enum::name)
                    .collect(toSet()));
            });
    }

    @GetMapping
    Map<String, Set<String>> findAll() {
        return registry;
    }

}

// EnumClassPathScanningCandidateComponentProvider.java

/**
 * EnumClassPathScanningCandidateComponentProvider is a specialization of {@link ClassPathScanningCandidateComponentProvider}
 * that only takes enum values into account.
 *
 * Furthermore it overrides the default behaviour of the {@link ClassPathScanningCandidateComponentProvider}
 * that checks that the classes that are found on the classpath are non-abstract. By their definition, an
 * enum that contains abstract methods or implements an interface is abstract and ignored.
 * This does not serve our purpose, hence the specialisation.
 */
@Component
class EnumClassPathScanningCandidateComponentProvider extends ClassPathScanningCandidateComponentProvider {

    EnumClassPathScanningCandidateComponentProvider() {
        super(false);
        addIncludeFilter(new IsEnumFilter());
    }

    /**
     * Determine whether the given bean definition qualifies as candidate.
     *
     * The default implementation checks whether the class is concrete
     * but this is does not work for us because an enum is considered abstract
     * when it implements an interface or has an abstract method.
     *
     * The JavaDoc of the default implementation also states that
     * this behaviour can be overridden in subclasses.
     *
     * @param beanDefinition the bean definition to check
     * @return whether the bean definition qualifies as a candidate component
     */
    @Override
    protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
        return beanDefinition.getMetadata().isIndependent();
    }

    private static class IsEnumFilter implements TypeFilter {

        @Override
        public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
            String className = metadataReader.getClassMetadata().getClassName();
            Class<Enum> clazz = Classes.forName(className);
            return clazz.isEnum();
        }
    }
}

Getting started.

We assume you have a working Redux project, if you do not yet have Redux add Redux to your project by following the Redux's instructions.

We also assume that you have redux-form installed via the instructions provided on the website.

First install the following dependencies in the package.json:

  1. "react-redux": "5.0.3",
  2. "redux": "3.6.0",

Now add the constraints-reducer to your rootReducer for example:

import { combineReducers } from 'redux';

import { EnumsStore, enums } from 'mad-spring-enum';

export interface Store {
  enums: EnumsStore
};

// Use ES6 object literal shorthand syntax to define the object shape
const rootReducer: Store = combineReducers({
  enums
});

export default rootReducer;

This should add the EnumsStore to Redux, which will store the enums from the Spring back-end.

Next you have to configure the enums module:

import { createStore } from 'redux';
import { configureEnums } from 'mad-spring-enum';

export const store = createStore(
  rootReducer,
);

configureEnums({
   // The URL which will provide the enums over a GET request.
  enumsUrl: '/api/enums',

  // Whether or not the 'enumsUrl' should be called with authentication.
  needsAuthentication: true,

  // The dispatch function for the Redux store.
  dispatch: store.dispatch,

  // A function which returns the latests EnumsStore from Redux.
  enumsStore: () => store.getState().enums
});

The enums module must be configured before the application is rendered.

Finally you will have load the enums from the back-end using the loadEnums function. If in order for the constraints to be loaded you need to be logged in, you should load the enums as soon as you know that you are logged in:

import { loadEnums } from 'mad-spring-enum';
import { login } from 'somewhere';

class Login extends Component {
  doLogin(username, password) {
    login({ username, password })
      .then(loadEnums); // Load enums ASAP
  }

  render() {
    // Render here which calls doLogin
  }
}

If you do not need a login before you can fetch the enums simply fetch them using loadEnums as soon as possible.

Usage

Now assuming you have an '' from the back-end and you want to use it in the front-end, you can retrieve the values of the enum by calling:

import { getEnum, EnumValues } from 'mad-spring-enum';
import type { EnumValues } from 'mad-spring-enum';

const userRoles: EnumValues = getEnum('UserRole'));

// now use userRoles as you please, it should be an array of strings.