GithubHelp home page GithubHelp logo

hygraph / management-sdk Goto Github PK

View Code? Open in Web Editor NEW
47.0 28.0 20.0 307 KB

GraphCMS Management SDK

License: MIT License

TypeScript 99.98% JavaScript 0.02%
graphcms management-sdk migration-tool automation

management-sdk's Introduction

@graphcms/management

Programmatically manage GraphCMS project schema via migrations.

Version Downloads/week License Forks on GitHub minified + gzip size Contributors
Join us on SlackLogin to GraphCMS@GraphCMS


⚠️ @graphcms/management has been deprecated and will no longer receive support. Please use @hygraph/management-sdk instead. Follow this guide to migrate to the new SDK. More information on the new SDK can be found here. ⚠️


Quickstart

const { newMigration, FieldType } = require("@graphcms/management");

const migration = newMigration({ endpoint: "...", authToken: "..." });

const author = migration.createModel({
  apiId: "Author",
  apiIdPlural: "Authors",
  displayName: "Author",
});

author.addSimpleField({
  apiId: "firstName",
  displayName: "First Name",
  type: FieldType.String,
});
author.addSimpleField({
  apiId: "lastName",
  displayName: "Last Name",
  type: FieldType.String,
});

migration.run();

Install

npm install @graphcms/management --save-dev

Usage

Changes to your schema starts with a migration.

New Migration

A migration is scoped to an environment. To create a migration, the following parameters are required.

  • Authentication Token authToken.

    Can be retrieved from Settings > API Access on https://app.graphcms.com

  • Environment URL endpoint.

    Can be retrieved from Settings > Environments on https://app.graphcms.com

  • Migration Name name [optional].

    Every migration has a unique name. If unspecified, a name would be generated and will be part of the response of a successful migration.

    Subsequent migrations with same name will fail.

const { newMigration } = require("@graphcms/management");

const migration = newMigration({
  authToken,
  endpoint,
  name, // optional
});

Running a Migration

The run method runs the migration.

By default, migrations run in the background. Passing an optional boolean argument configures the migration to run in the foreground.

const foreground = true;

const result = migration.run(foreground);

if (result.errors) {
  console.log(result.errors);
} else {
  console.log(result.name);
}

Dry Run a Migration

A migration can be dry run to preview what changes would be applied.

const changes = migration.dryRun();

console.log(changes);

Updating an Entity

To update properties, specify the properties to be updated. All ommitted properties remain unmodified.

As a special case, apiId is a requirement because all entities are uniquely indentified by apiId.

To update the apiId, specify newApiId.

Locales

GraphCMS boasts a flexible localization API that you can use to publish content for all or specific locales in your project.

Create a Locale

To create a locale

migration.createLocale({
  apiId,
  displayName,
  description,
});

Update a Locale

To update a locale

migration.updateLocale({
  apiId,
  ... // properties to update
});

Delete a Locale

To delete a locale

migration.deleteLocale(apiId);

Stages

You can create your own content stages, and query content from these stages, as well as publish to.

Create a Stage

To create a stage

migration.createStage({
  apiId,
  displayName,
  description,
  isDefault,
  allowQueries,
  color,
});

Update a Stage

To update a stage

migration.updateStage({
  apiId,
  ... // properties to update
});

Delete a Stage

To delete a Stage

migration.deleteStage(apiId);

Enumerations

Enums values can only contain alphanumeric characters, and underscores.

Create a Enumeration

Create an enumeration with values.

const colors = migration.createEnumeration({
  apiId,
  displayName,
  description,
});

// add values
colors.addValue("Red");
colors.addValue("Green");

// or add multiple values at a time.
colors.addValue("Blue", "Yellow");

Update a Enumeration

Updating an enumeration and it's values.

const colors = migration.updateEnumeration({
  apiId,
  ... // properties to update.
});

colors.addValue("Black"); // add a new value
colors.updateValue("Red", "Dark Red"); // update existing value
colors.deleteValue("Blue"); // delete value

Delete Enumeration

To delete an enumeration and it's values

migration.deleteEnumeration(apiId);

Models

Your schema is defined by the models you create, and fields you add.

Create a Model

A model can be created by passing in the required parameters.

const modelName = migration.createModel({
  apiId, // must start with upper case letter
  apiIdPlural, // must start with upper case letter
  displayName,
  description,
});

Update a Model

To update a model

migration.updateModel({
  apiId, // required
  ... // properties to update
});

Delete a Model

To delete a model

migration.deleteModel(apiId);

Fields

Your schema is built up of GraphQL types. If you’re familiar working with GraphQL, you should feel right at home. GraphCMS supports all of the common GraphQL types you are used to, as well as some of its own.

Create a Field

To create a simple field.

const { FieldType } = require("@graphcms/management");

model.addSimpleField({
  apiId: '...',
  displayName: '...',
  type: FieldType.String,
});

String fields have several form renderers, including single line, multiline, markdown, and slug. You can set the form renderer as follows:

const { FieldType, Renderer } = require("@graphcms/management");

model.addSimpleField({
  apiId: '...',
  displayName: '...',
  type: FieldType.String,
  formRenderer: Renderer.MultiLine
});

To create an enumerable field.

model.addEnumerableField({
  apiId,
  displayName,
  enumerationApiId, // previously created enumeration.
});

To create a relational field.

const { RelationType } = require("@graphcms/management");

model.addRelationalField({
  apiId,
  displayName,
  relationType: RelationType.OneToOne,
  model, // the related model

  // optional but can be specified to customize the details.
  reverseField: {
    apiId,
    displayName,
  },
});

To create an asset field.

model.addRelationalField({
  apiId,
  displayName,
  model: "Asset", // this is compulsory to indicate Asset field.

  // optional but can be specified to customize the details.
  reverseField: {
    apiId,
    displayName,
  },
});

To create a union field.

const { RelationType } = require("@graphcms/management");

model.addUnionField({
  apiId,
  displayName,
  relationType: RelationType.OneToOne,
  models, // list of related models

  // optional but can be specified to customize the details.
  reverseField: {
    apiId,
    displayName,
  },
});

Update a Field

To update a field, firstly retrieve the model.

const model = migration.updateModel({...}) // to update the model
const model = migration.model(apiId) // to only retrieve the model

Updating simple field

model.updateSimpleField({
  apiId,
  ... // properties to update
})

Updating enumerable field

model.updateEnumerableField({
  apiId,
  ... // properties to update
})

Updating relational field

model.updateRelationalField({
  apiId,
  ... // properties to update
})

Updating union field

model.updateUnionField({
  apiId,
  models, // list of related models
  ... // properties to update
})

Deleting a Field

To delete a field

model.deleteField(apiId);

Contributors

Thanks goes to these wonderful people (emoji key):

Local Development

To update the Management API schema this SDK depends on you must run npm run generate.

PR titles must follow Conventional Commits to publish to NPM automatically.

management-sdk's People

Contributors

aea7 avatar brunoscheufler avatar derozn avatar flexzuu avatar joelpierre avatar mrloh avatar notrab avatar rajatsharma avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

management-sdk's Issues

[TypeScript] addRelationalField suddenly requires the deprecated field 'isHidden' to be explicitly set

This might come from the latest changes that added the visibility setting.

Up until recently (2 weeks ago it was still ok), the code below was perfectly valid:


schedule.addRelationalField({
  apiId: 'zoomedInImage',
  displayName: 'Zoomed In Image',
  model: 'Asset',
  relationType: RelationType.ManyToOne,
  reverseField: {
    apiId: 'relatedScheduleZoomedInImage',
    displayName: 'related Schedule Zoomed In Image',
  },
});

However, this now stopped passing TypeScript validation as the field 'isHidden' is missing.
The error states as such:

Argument of type '{ apiId: string; displayName: string; model: string; relationType: RelationType.ManyToOne; reverseField: { apiId: string; displayName: string; }; }' is not assignable to parameter of type 'Omit<PartialBy<RelationalFieldArgs, "reverseField" | "type">, "modelApiId">'.
Property 'isHidden' is missing in type '{ apiId: string; displayName: string; model: string; relationType: RelationType.ManyToOne; reverseField: { apiId: string; displayName: string; }; }' but required in type 'Omit<PartialBy<RelationalFieldArgs, "reverseField" | "type">, "modelApiId">'.ts(2345)
model.d.ts(14, 5): 'isHidden' is declared here.

Even though isHidden is deprecated, it is now compulsory to add it using TypeScript and the SDK.
Adding visibility and not adding isHidden is also not an option for TypeScript.

Setting a field position doesn't seem to work

When I use the management SDK to set a field position it doesn't work, it does however place the field at the top of the UI.

It may be better to take an apiId instead of a number value or alternatively take an apiId so I can say e.g "Place this field after X field"

...addSimpleField({
  positionAfter: 'example' // String
})

Cannot update a field to be required once already created

I have a model with a simple field I created. In the next migration I wanted to make this field required, however the update was being rejected, even though I was passing a migration value.

When testing I noticed that I had to delete every entry and then I could update the field to be required.

In the UI this isn't an issue as it asks for a migration value. I assume there is some sort of ordering of mutations issue meaning that the migration is rejected?

e.g

model.addSimpleField({
  apiId: 'label',
  displayName: 'Label',
  type: FieldType.String,
  isLocalized: true
});

on next run when content has been added (this fails)

model.updateSimpleField({
  apiId: 'label',
  migrationValue: 'test',
  isRequired: true
});

Feature Request: add createComponent method to exposed api

Hey there, I'm looking to migrate a project to graphcms / hygraph and need to generate my types through the sdk. Everything seems possible except for the components. The schema types seemed to already exist in the generated file, is this possible to add?

Add NPM release action

Using the same GH action as the Gatsby source plugin, we should release this package automatically.

Before this is done we need to tag the current version, AND decide how we proceed with schema changes. Are they major or minor releases.

Update Simple Field doesn't work for validation.

Hi,

I've noticed that updating a validation on field using updateSimpleField doesn't work. When I try to do that I'm getting an error:

Error: field validations not supported for undefined at extractFieldValidations

From what I was able to find it was happen because updateSimpleField use extractFieldValidations which require a type to work:

Zrzut ekranu 2022-02-16 o 20 48 20

But the typescript type definition for the updated model does not allow us to pass it. (This is understandable, we can't pass the type because we can't update it.) :

Zrzut ekranu 2022-02-16 o 20 55 38

Temporary workaround is to pass a type in updateSimpleField and disable warning from typescript. The type must be the same as the field already exists in:

Zrzut ekranu 2022-02-16 o 20 56 34

missing permission for action: SIDEBAR_ELEMENT_CREATE

Hi,

I can't run any migrations anymore in my account, when I try while i'm logged in, I get this error message:
missing permission for action: SIDEBAR_ELEMENT_CREATE
I have all management API permissions checked.
Same migration worked fine a couple of weeks ago.

`updateUnionField()` does not support `visibility: hidden` for reverse fields.

client.updateUnionField({
    apiId: 'target',
    displayName: 'Placement target',
    modelApiId: 'DynamicRow',
    reverseField: {
      modelApiIds: [
        <VARIOUS MODELS>,
      ],
      // Here should be an option for visibility, as is done in client.createUnionField. 
      // This would set the visibility for the reverse fields.
    },
    visibility: VisibilityTypes.ReadWrite, // This sets the visibitlity for the DynamicRow model.
  })

Right now I am trying to update my union field, adding visibility: hidden for the reverse fields. This is not possible with the current management SDK. Although it is supported in createUnionField(), I can't delete my model because I would lose all my entries.

Also displayName should be supported for reverseField in updateUnionField().

slug generation

I noticed that from the management sdk it is not possible or at least not documented on how to treat a slug type so that it generates the slug based on other field. e.g: generate slug based on post id or name

Updating a union type doesn't copy existing settings

Hi,

I've noticed that when updating a UnionField to include new models, the existing settings for this union aren't added to the new models.

For example when adding a new model to the union, the apiOnly state is not applied to the new model, but continues to exist on the older models.

Existing

Screenshot 2021-11-17 at 09 07 42

New

Screenshot 2021-11-17 at 09 07 49

As you can see, the visibility on the New one does not include the API Only from the existing one.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.