@dagens/sanity-orm v1.10.1
Sanity ORM
A Typescript based wrapper around the Sanity API
Install
Install the package and the reflect-metadata shim:
npm install @dagens/sanity-orm reflect-metadatareflect-metadata is required by class-transformer and must be imported once before @dagens/sanity-orm
Transformer type
To tell class transformer which types to use, outside the simple types you should use the @Type decorator. Example
npm install class-transformerValidation
If you want to enable validation install class-validator as well.
npm install class-validatorUsage
Initialization
Initialize with the initialize helper:
import { Document, initialize, getRepository } from '@dagens/sanity-orm';
// Create a Sanity javascript client instance
const sanityClient = require('@sanity/client');
const client = sanityClient({
  projectId: process.env.SANITY_PROJECT_ID,
  dataset: process.env.SANITY_DATASET,
  token: process.env.SANITY_TOKEN,
  apiVersion: '2021-12-30',
  useCdn: false,
});
// Initialize sanity-orm
initialize(client);Note: initialize must only be run once
Example
This example uses dotenv, which is not required, just used as an example of externally importing secrets
import 'reflect-metadata'; // Must be required at the top level
import * as dotenv from 'dotenv';
import { Type } from 'class-transformer';
import { Document, initialize, getRepository } from '@dagens/sanity-orm';
dotenv.config();
// Create a Sanity javascript client instance
const sanityClient = require('@sanity/client');
const client = sanityClient({
  projectId: process.env.SANITY_PROJECT_ID,
  dataset: process.env.SANITY_DATASET,
  token: process.env.SANITY_TOKEN,
  apiVersion: '2021-12-30',
  useCdn: false,
});
// Initialize sanity-orm
initialize(client);
// Define a model
@Document('movie')
class Movie {
  _id!: string;
  _type!: string;
  @Type(() => Date)
  _createdAt!: Date;
  title!: string;
}
// Retrieve a repository for the model
const repo = getRepository(Movie);
// Query movis and print the result
repo.query().raw('*[_type == "movie"]').find().then((models: Movie[]) => {
  models.forEach((model: Movie) => {
    console.log(model._id, model._type, model.title, model._createdAt);
  })
});Validation
Follow the validation section under installation.
import 'reflect-metadata'; // Must be required at the top level
import * as dotenv from 'dotenv';
import { Type } from 'class-transformer';
import {
  IsString,
  IsOptional,
  Equals,
} from 'class-validator';
import { Document, initialize, getRepository } from '@dagens/sanity-orm';
dotenv.config();
// Create a Sanity javascript client instance
const sanityClient = require('@sanity/client');
const client = sanityClient({
  projectId: process.env.SANITY_PROJECT_ID,
  dataset: process.env.SANITY_DATASET,
  token: process.env.SANITY_TOKEN,
  apiVersion: '2021-12-30',
  useCdn: false,
});
// Initialize sanity-orm
initialize(client, {
  validateQueryResult: true,
  validationOptions: {
    whitelist: true,
    forbidNonWhitelisted: true,
  },
});
// Define a model
@Document('movie')
class Movie {
  @IsString()
  _id!: string;
  @Equals('movie')
  _type!: string;
  @IsOptional()
  @Type(() => Date)
  _createdAt!: Date;
  @IsString()
  title!: string;
}
// Retrieve a repository for the model
const repo = getRepository(Movie);
// Query movis and print the result
repo.query().raw('*[_type == "movie"]').find().then((models: Movie[]) => {
  models.forEach((model: Movie) => {
    console.log(model._id, model._type, model.title, model._createdAt);
  })
});The validation rules given in initialize are:
| Name                   | Description                                                                                                                                                  |
|------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------|
| validateCreateUpdate | Validate on insertion and update. Recommended: true                                                                                                        |
| validateQueryResult  | Validate on retrieval. Useful when moving to an ORM and not being quite sure of the integrity of the data already in the system                              |
| validationOptions    | Validation options given to class-validator, refer to class-transformers readme for decorators and options |
Development
Testing
Sanity has no in memory database that makes testing easy, so a live database is used instead. Go set one up on sanity.io. Then create a .env file in the root of the repo with the following contents:
SANITY_PROJECT_ID=<your-project-id>
SANITY_DATASET=<name-of-your-dataset>
SANITY_TOKEN=<your-access-token>Running the tests should be as easy as:
npm run test2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago