@euc-development/shp-helpers

2.1.0 • Public • Published

Intro

This is a package specifically for EUC Development team, which contains helper functions and basic setup for SharePoint front-end development with NuxtJS framework.

Table of Contents

Installation

npm i @euc-development/shp-helpers

Requirements

  • NodeJs v20
  • NuxtJs / VueJs v3
  • Vuetify v3

Setup

The whole setup should be in a single place where it can run before the whole app is initialize. I chose to do this in a global middleware 01.init.global.js.

Setup Constants

The following constants can be set up, which also have a default value:

export const constants = {
	adminGroupName: 'EUC Development',
	iamAdminGroupName: 'IAM Administration',
}

To set this up, import the variable from the package and assign a value:

import { constants } from '@euc-development/shp-helpers'

constants.adminGroupName = ExtendedGroup.GROUP_EUC
constants.iamAdminGroupName = ExtendedGroup.GROUP_IAM_ADMIN

Initialize Package

First you need to import the initShpHelpers function the package and then use it with the following arguments:

  • axios - basic axios instance, no need to do any setup, the package should handle all
  • t - the $t translation instance of Nuxt
  • toast - the toast notification instance (vue-toast-notification)
import { initShpHelpers } from '@euc-development/shp-helpers'
import { t } from '~/plugins/i18n'
import { toast } from '~/plugins/toast'
import axios from 'axios'

initShpHelpers(axios, t, toast)

To get the latter from Nuxt, you can do the following in a plugin:

// toast.js plugin

import ToastPlugin from 'vue-toast-notification'

import 'vue-toast-notification/dist/theme-sugar.css'

export let toast

export default defineNuxtPlugin(app => {
	app.vueApp.use(ToastPlugin, {
		position: 'top-right',
		duration: 5000,
	})

	toast = app.vueApp.config.globalProperties.$toast
})

// i18n.js plugin

export let t
export let i18n

export default defineNuxtPlugin(app => {
	t = app.vueApp.config.globalProperties.$t
	i18n = app.vueApp.config.globalProperties.$i18n
})

Setup Axios

Axios Queries is a custom library to easily interact with the SharePoint API. Import the axiosService variable from the package and call the setupAxios method with the following parameters:

  • axios - basic axios instance, no need to do any setup, the package should handle all
  • proxyLocalHostUrl - for example 'http://localhost:8080'
  • sharepointServerUrl- for example 'https://ing.sharepoint.com'
  • serverRelativeUrl - for example '/sites/360-competency-assessment-tool-uat_cs'
import { SERVER_RELATIVE_URL, PROXY_LOCAL_HOST_URL, SHAREPOINT_SERVER_URL } from '~/global/config'
import axios from 'axios'

axiosService.setupAxios(axios, PROXY_LOCAL_HOST_URL, SHAREPOINT_SERVER_URL, SERVER_RELATIVE_URL)

After fetching the user instance, you need to also set up the token of the user to be able to send POST request.

axiosService.token = currentUser.token

Typical Setup In One Place

import LinkFixerService from '@euc-development/shp-helpers/classes/Services/LinkFixerService'
import { axiosService, constants } from '@euc-development/shp-helpers'
import { currentUser, groups, pkg, users } from '~/classes/Store'
import UserSwitcher from '~/classes/UserSwitcher'
import packageJson from '~/package.json'
import { SERVER_RELATIVE_URL, PROXY_LOCAL_HOST_URL, SHAREPOINT_SERVER_URL } from '~/global/config'
import axios from 'axios'
import ExtendedGroup from '~/classes/ExtendedGroup'
import { initShpHelpers } from '@euc-development/shp-helpers'
import { t } from '~/plugins/i18n'
import { toast } from '~/plugins/toast'

// const linkFixerService = new LinkFixerService()
// linkFixerService.fix()

let initialLoadCompleted = false

export default defineNuxtRouteMiddleware(async (to, from) => {
	if (initialLoadCompleted) return

	constants.adminGroupName = ExtendedGroup.GROUP_EUC
	constants.iamAdminGroupName = ExtendedGroup.GROUP_IAM_ADMIN

	initShpHelpers(axios, t, toast)

	axiosService.setupAxios(axios, PROXY_LOCAL_HOST_URL, SHAREPOINT_SERVER_URL, SERVER_RELATIVE_URL)

	pkg.set(packageJson)

	const promises = []

	promises[promises.length] = currentUser.fetch(UserSwitcher.getSelectedUserId())
	promises[promises.length] = users.fetch()
	promises[promises.length] = groups.fetch()

	try {
		await Promise.all(promises)

		axiosService.token = currentUser.token

		window.setInterval(() => {
			currentUser.fetch(UserSwitcher.getSelectedUserId())
		}, 480000)

		initialLoadCompleted = true
	} catch (error) {
		console.error(error)
	}
})

Axios Queries

To use the library in the application anywhere, import AxiosQueries static class and use its methods:

import AxiosQueries from '@euc-development/shp-helpers/classes/AxiosQueries/AxiosQueries'

const circles = await AxiosQueries.fetchListItems('Circles', {
	select: 'Id,Title,superCircle/Id,superCircle/Title,Created',
	expand: 'superCircle',
})

User Class

To use the User class, simply import it:

import User from '@euc-development/shp-helpers/classes/User'

Filter Component

To use the filter component, first import the lang file to your project:

import filtersEnLocales from '@euc-development/shp-helpers/locales/en/filters-locale-en'
export default {
	$vuetify: en,

	iam: iamEnLocales,
	migrations: migrationsEnLocales,
	filters: filtersEnLocales,
}

Next import the component to your Vue page / component:

import FilterWrapper from '@euc-development/shp-helpers/components/filter/filter-wrapper.vue'

Send the required props to it:

<filter-wrapper :items="circles" :filter-data="filters" v-model="filteredCircles" />
const headers = [
	{ title: 'Id', value: 'Id', sortable: true },
	{ title: 'Title', value: 'Title', sortable: true },
	{ title: 'Super Circle', value: 'superCircle.Title' },
]

const filters = [
	// { type: 'number', paramPath: 'Id', label: 'Id' },
	// { type: 'string', paramPath: 'Title', label: 'Title String' },
	{ type: 'selectString', paramPath: 'superCircle.Title', label: 'superCircleTitle' },
	// { type: 'selectObject', paramPath: 'superCircle', label: 'superCircle' },
	// { type: 'date', paramPath: 'Created', label: 'Created' },
	{ type: 'date', paramPath: 'Created', label: 'Created', dateType: 'to' },
]
  • items - array of items you would like to filter
  • v-model - should be empty array initially, filtered items will be returned this way
  • filter-data - setup of the folder, see next section

Optional props:

  • cols (default: 12) - vuetify row columns setup
  • sm (default: 6) - vuetify row columns setup
  • md (default: 3) - vuetify row columns setup
  • lg - vuetify row columns setup
  • xl - vuetify row columns setup

Filter Data

Array of objects, where each object represent a filter field. Required parameters for each field:

  • type - type of the filter
    • number - the corresponding parameter should be a number. A free text field is generated (limited to numbers), searches number in a number field.
    • string - the corresponding parameter should be a string. A free text field is generated, searches string in a string field.
    • bool - the corresponding parameter should be a boolean. Two options (yes/no) are generated to a dropdown list.
    • selectNumber - the corresponding parameter should be a number. All available options are generated to a dropdown field, where multiselect is possible.
    • selectString - the corresponding parameter should be a string. All available options are generated to a dropdown field, where multiselect is possible.
    • selectObject - the corresponding parameter should be an object with Id and Title values. All available options are generated to a dropdown field.
    • selectObjectMulti - the corresponding parameter should be an array of objects with Id and Title values. All available options are generated to a dropdown field.
    • date - the corresponding parameter should be a date in any string format acceptable by Moment package
  • paramPath - path to the parameter of the item
  • label - label / placeholder in the input field

Optional parameters:

  • queryParam - Default: paramPath. The query parameter for the field in the URL.
  • sortBy - Default: Title. Available for selectObject and selectObjectMulti. Available values: Id or Title.
  • idParam - Default: Id. Available for selectObject and selectObjectMulti. The id value available at paramPath.
  • titleParam - Default: Title. Available for selectObject and selectObjectMulti. The title/text value available at paramPath.
  • cols, sm, md, lg, xl - overrides the column settings for the specific field
  • dateType - available only for date filter, possible values:
    • exact - this is the default if not provided
    • from - filters dates equal or bigger than the search string
    • to - filters dates equal or smaller than the search string

Data Table Pagination Service

This service works together with the data table component of Vuetify. It adds query parameters to the url, when pagination, items per page or sorting is changed, so that after refresh the table looks the same.

First import the service:

import DataTablePaginationService from '@euc-development/shp-helpers/classes/Services/DataTablePaginationService'

Then add the parameters to the data table:

<v-data-table
	:items="filteredCircles"
	:headers="headers"
	@update:options="dataTablePaginationService.updateOptions()"
	v-model:page="dataTablePaginationService.page.value"
	v-model:items-per-page="dataTablePaginationService.itemsPerPage.value"
	v-model:sort-by="dataTablePaginationService.sortBy.value"
/>

Lastly call the setOptions function after the component or page is mounted:

onMounted(() => {
	dataTablePaginationService.setOptions()
})

IAM Module

This is a plugin which delivers the whole IAM section to the app with minimal setup.

IAM Module Setup

Import the locales to the app:

import iamEnLocales from '@euc-development/shp-helpers/locales/en/iam-locale-en'

export default {
	$vuetify: en,

	iam: iamEnLocales,
}

IAM Module Usage

Create a page for User and one for Group managemnet and simply import the components:

// users.vue

<template>
	<IamUsers />
</template>

<script setup>
import IamUsers from '@euc-development/shp-helpers/components/iam/users/iam-users.vue'
import { t } from '~/plugins/i18n';

useHead({ title: t('page_titles.iam.users') })

definePageMeta({
	middleware: 'iam-can-manage-iam-zone',
})
</script>
// groups.vue

<template>
	<IamGroups />
</template>

<script setup>
import IamGroups from '@euc-development/shp-helpers/components/iam/groups/iam-groups.vue'
import { t } from '~/plugins/i18n';

useHead({ title: t('page_titles.iam.groups') })

definePageMeta({
	middleware: 'iam-can-manage-iam-zone',
})
</script>

Migrations Module

This is a plugin which delivers migrations to the app with minimal setup.

Migrations Setup

Create migrations.js file in the root of the project and paste the following code:

import createMigration from '@euc-development/shp-helpers/create-migration.js'

createMigration()

Next add the following script to the package.json file:

"create:migration": "node ./migrations.js --create"

Next create a migrations folder in the root folder with an index.js file in it. Here you need to import all migration files and export them as an array.

// migrations/index.js

export default [
	(await import('~/migrations/20231011150548_CreateExampleList')).default
]

Create a new list on the SharePoint site, which you are using with the application. Recommended name is Migrations. Information about already executed migrations needs to be saved here.

Create a page, where you import the main component to interact with the migrations:

  • migration-classes-original - these are the migration files
  • migrations-list-title - title of the migrations list on the SharePoint site
// migrations.vue

<template>
   <Migrations :migration-classes-original="migrationClasses" migrations-list-title="Migrations" />
</template>

<script setup>
import { t } from '~/plugins/i18n';
import migrationClasses from "~/migrations/index";
import Migrations from '@euc-development/shp-helpers/components/migrations/migrations.vue'

useHead({ title: t('page_titles.admin.migrations') })

definePageMeta({
	middleware: 'admin-can-manage-admin-zone',
})
</script>

Migrations Usage

You should be able to create migration files with the following command:

npm run create:migration -- --name=CreateExampleList

If successful, a new JS file should be created in the migrations folder of the project:

// 20231011150548_CreateExampleList.js

import List from '@euc-development/shp-helpers/classes/Migrations/Lists/List'
import ListAttributeTypes from '@euc-development/shp-helpers/classes/Migrations/Lists/ListAttributeTypes'

const exmapleList = new List('Example')

export default class CreateExampleList {
	static createdAt = 20231011150548
	static title = 'CreateExampleList'

	async up() {
		await exmapleList.create()
	}

	async down() {
		await exmapleList.remove()
	}
}

The up method is called when migrating, the down method is called when rollbacking.

Migrations Page

To interact with the migrations, navigate to the page, where you imported the main component. If you open the page, you should see two tables:

  • already migrated migrations
  • not migrated migrations

Also you have four buttons available:

  • Migrate - migrate the next migration in line
  • Migrate All- migrate all migrations
  • Rollback - rollback the previous migration in line
  • Rollback All - rollback all migrations

Additional Classes and Services

Link Fixer Service

To be added

Utilities Service

import UtilitiesService from '@euc-development/shp-helpers/classes/Services/UtilitiesService'
static preventEnterSubmitForm

This function can be called upon app startup and it disables form submission by pressing enter by default.

Locale Selector

To be added

Excel Class

import Excel from '@euc-development/shp-helpers/classes/Excel'

Contains methods and attributes to help interact with XLSX package - read and create Excel files. For more info please refer to the implementation.

Group Classes

import Group from '@euc-development/shp-helpers/classes/Group'
import Groups from '@euc-development/shp-helpers/classes/Groups'

Contains methods and attributes to help interact with group objects on Sharepoint. For more info please refer to the implementation.

Permission Classes

import Permission from '@euc-development/shp-helpers/classes/Permission'
import Permissions from '@euc-development/shp-helpers/classes/Permissions'

Contains methods and attributes to help interact with permission objects on Sharepoint. For more info please refer to the implementation.

Model Class

import Model from '@euc-development/shp-helpers/classes/Model'

Contains methods and attributes to help interact with permission objects on Sharepoint. For more info please refer to the implementation.

Pkg Class

import Pkg from '@euc-development/shp-helpers/classes/Pkg'

Contains methods and attributes to help interact with package.json file. For more info please refer to the implementation.

User Class

Contains methods and attributes to help interact with user objects on Sharepoint. For more info please refer to the implementation.

URL Class

This is a custom class to manage the URL and its query parameters. To use it, simply import it. For more info please refer to the implementation.

import Url from "@euc-development/shp-helpers/classes/Url" 

Readme

Keywords

none

Package Sidebar

Install

npm i @euc-development/shp-helpers

Weekly Downloads

7

Version

2.1.0

License

ISC

Unpacked Size

193 kB

Total Files

81

Last publish

Collaborators

  • euc-development